java 基本集合操作
排序
public static void main(String[] args) {
List<Demo> demoList = new ArrayList<Demo>();
demoList.add(new Demo(1, 2));
demoList.add(new Demo(1, 3));
demoList.add(new Demo(1, 5));
demoList.add(new Demo(4, 2));
demoList.add(new Demo(1, 2));
demoList.add(new Demo(2, 4));
demoList.add(new Demo(1, 2));
demoList.add(new Demo(2, 5));
demoList.add(new Demo(1, 2));
Collections.sort(demoList, new Comparator<Demo>() {
public int compare(Demo d1, Demo d2) {
if (d2.getAge() == d1.getAge()) {
return d2.getSort() - d1.getSort();
} else {
return d2.getAge() - d1.getAge();
}
};
});
// [[4:2], [2:5], [2:4], [1:5], [1:3], [1:2], [1:2], [1:2], [1:2]]
System.out.println(demoList);
Date q1 = new Date();
Calendar c = java.util.Calendar.getInstance();
c.add(Calendar.DATE, 1);
Date q2 = c.getTime();
System.out.println(q2.compareTo(q1)); //1
}
删除
public static void main(String[] args) {
List<Demo> coll = new ArrayList<Demo>();
coll.add(new Demo(1, 2));
coll.add(new Demo(1, 3));
coll.add(new Demo(4, 2));
coll.add(new Demo(2, 4));
coll.add(new Demo(1, 2));
coll.add(new Demo(2, 5));
coll.add(new Demo(1, 2));
for (Iterator<Demo> it = coll.iterator(); it.hasNext();)
if (it.next().getAge() == 1)
it.remove();
System.out.println(coll); //[[4:2], [2:4], [2:5]]
Map<String, Demo> map = new HashMap<String, Demo>();
for (int i = 0; i < coll.size(); i++) {
map.put("" + i, coll.get(i));
}
for (Iterator<Map.Entry<String, Demo>> it = map.entrySet().iterator(); it.hasNext();) {
if (it.next().getValue().getAge()== 4)
it.remove();
}
System.out.println(map); //{2=[2:5], 1=[2:4]}
}
class Demo {
private int sort;
private int age;
public Demo(int age, int sort) {
this.sort = sort;
this.age = age;
}
public Demo() {}
public int getSort() {
return sort;
}
public int getAge() {
return age;
}
public String toString() {
return "[" + age + ":" + sort + "]";
}
}