`
tooby
  • 浏览: 117388 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Java Map借助key List的排序

    博客分类:
  • Java
 
阅读更多
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


public class Test {
	public static void main(String[] args) {
		Map<String, ChartSeries> map = new HashMap<String, ChartSeries>();
		// 随机生成40个对象
		Random random = new Random();
		for (int i = 0; i < 40; i++) {
			ChartSeries t = new ChartSeries();
			t.setY(new Double(random.nextInt(100) + 1));
			map.put(String.valueOf(i), t);
		}
		
		List<Map.Entry<String, ChartSeries>> infoIds =
			    new ArrayList<Map.Entry<String, ChartSeries>>(map.entrySet());
		
		Collections.sort(infoIds, new Comparator<Map.Entry<String, ChartSeries>>() {   
		    public int compare(Map.Entry<String, ChartSeries> o1, Map.Entry<String, ChartSeries> o2) {      
		        //return (o2.getValue() - o1.getValue()); 
				if (o1.getValue().getY() > o2.getValue().getY()) {
					return -1;
				} else if (o1.getValue().getY() == o2.getValue().getY()) {
					return 0;
				} else
					return 1;
		    }
		});
		
		// 以此输出年龄
		for (Map.Entry<String, ChartSeries> i : infoIds) {
			System.out.println(i.getValue().getY());
		}
	}
}

/**
 * 
 * 必须实现“Comparator”接口
 * 
 * 以age属性进行排序(当然也可以根据多个属性组合排序,此处不再演示)
 */
class Dog implements Comparator<Dog> {
	private int age;

	public Dog() {

	}

	public Dog(int age) {
		this.age = age;
	}

	/**
	 * 按年龄升序
	 */
	public int compare(Dog o1, Dog o2) {
		if (o1.age < o2.age) {
			return -1;
		} else if (o1.age == o2.age) {
			return 0;
		} else
			return 1;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

class ChartSeries implements Comparator<ChartSeries> {
	private String color;
	private Double y;

	public ChartSeries(){
		
	};
	
	public ChartSeries(String colorValue, Double yValue) {
		this.color = colorValue;
		this.y = yValue;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public Double getY() {
		return y;
	}

	public void setY(Double y) {
		this.y = y;
	}

	/**
	 * order by y
	 */
	public int compare(ChartSeries o1, ChartSeries o2) {
		if (o1.y < o2.y) {
			return -1;
		} else if (o1.y == o2.y) {
			return 0;
		} else
			return 1;
	}

}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics