Java Map 按value排序、TreeMap、linkedHashMap笔记

	public static void main(String[] args) {
		Map<String,Object[]> m = new HashMap<String, Object[]>();
		
		m.put("1", new Object[]{1,"ff"});
		m.put("2", new Object[]{11,"dd"});
		m.put("3", new Object[]{23,"ee"});
		m.put("4", new Object[]{11,"gg"});
		
		for (Iterator iterator = m.entrySet().iterator(); iterator.hasNext();) {
			Entry<String, Object[]> type = (Entry<String, Object[]>) iterator.next();
			Object[] obj1s = ((Entry<String,Object[]>)type).getValue();
			System.out.println(type.getKey()+"-->"+obj1s[0]+"::"+obj1s[1]);
		}
		
		
		ArrayList<Entry<String,Object[]>> list = new ArrayList<Entry<String,Object[]>>(m.entrySet());   
		//根据value排序
		Collections.sort(list, new Comparator<Object>() {
			public int compare(Object e1, Object e2) {

				Object[] obj1s = ((Entry<String, Object[]>) e1).getValue();
				Object[] obj2s = ((Entry<String, Object[]>) e2).getValue();
				// String obj1 = (String) obj1s[1];
				// String obj2 = (String) obj2s[1];

				Integer obj1 = (Integer) obj1s[0];
				Integer obj2 = (Integer) obj2s[0];

				return obj1.compareTo(obj2);

			}
		});  
		System.out.println("============");
		
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			Entry<String, Object[]> type = (Entry<String, Object[]>) iterator.next();
			Object[] obj1s = ((Entry<String,Object[]>)type).getValue();
			System.out.println(type.getKey()+"-->"+obj1s[0]+"::"+obj1s[1]);
		}
		
		//LinkedHashMap记录元素顺序,默认为插入顺序输出,够着函数可以指定,为访问最近的元素输出,LUR算法
		Map<String,Object[]> linked = new LinkedHashMap<String, Object[]>(20,0.75f,true);
		
		linked.put("1", new Object[]{1,"ff"});
		linked.put("2", new Object[]{11,"dd"});
		linked.put("3", new Object[]{23,"ee"});
		linked.put("4", new Object[]{11,"gg"});
		
		System.out.println("============");
		
		linked.get("4");
		linked.get("4");
		linked.get("1");
		linked.get("1");
		linked.get("4");
		
		for (Iterator iterator = linked.entrySet().iterator(); iterator.hasNext();) {
			Entry<String, Object[]> type = (Entry<String, Object[]>) iterator.next();
			Object[] obj1s = ((Entry<String,Object[]>)type).getValue();
			System.out.println(type.getKey()+"-->"+obj1s[0]+"::"+obj1s[1]);
		}

		//TreeMap实现排序,sortedMap是TreeMap的实现
		TreeMap<String,Object[]> tree = new TreeMap<String, Object[]>();
		
		tree.put("1", new Object[]{1,"ff"});
		tree.put("6", new Object[]{11,"dd"});
		tree.put("3", new Object[]{23,"ee"});
		tree.put("4", new Object[]{11,"gg"});
		
		System.out.println("============");

		
		for (Iterator iterator = tree.entrySet().iterator(); iterator.hasNext();) {
			Entry<String, Object[]> type = (Entry<String, Object[]>) iterator.next();
			Object[] obj1s = ((Entry<String,Object[]>)type).getValue();
			System.out.println(type.getKey()+"-->"+obj1s[0]+"::"+obj1s[1]);
		}
		
	}
	

 

你可能感兴趣的:(java,算法)