java中的接口是类吗
269
2023-05-13
List对象去重和按照某个字段排序的实现方法
1、List
People类
public class People {
private int id;
private String name;
private Date createDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
}
main方法
public static void main(String[] args) throws Exception{
List
People p1 = new PeoEeDJtVBuple();
p1.setId(1);
p1.setName("赵");
list.add(p1);
People p2 = new People();
p2.setId(2);
p2.setName("钱");
list.add(p2);
People p3 = new People();
p3.setId(3);
p3.setName("孙");
list.add(p3);
People p4 = new People();
p4.setId(4);
p4.setName("李");
list.add(p4);
People p5 = new People();
p5.setId(5);
p5.setName("周");
list.add(p5);
list.add(p1);
for(People p : list){
System.out.println(p);
}
System.out.println("==========================");
Set
list.clear();
list.addAll(new ArrayList
for(People p : list){
System.out.println(p);
}
}
2、List
自定义Comparator
public class MyComparator implements Comparator
@Override
public int compare(People p1, People p2) {
return p1.getCreateDate().compareTo(p2.getCreateDate());
}
}
main方法
public static void main(String[] args) throws Exception{
List
People p1 = new People();
p1.setId(1);
p1.setName("赵");
p1.setCreateDate(new Date(new Date().getTime() + 1000));
list.add(p1);
People p2 = new People();
p2.setId(2);
p2.setName("钱");
p2.setCreateDate(new Date(new Date().getTime() + 8000));
list.add(p2);
People p3 = new People();
p3.setId(3);
p3.setName("孙");
p3.setCreateDate(new Date(new Date().getTime() + 7000));
list.add(p3);
People p4 = new People();
p4.setId(4);
p4.setName("李");
p4.setCreateDate(new Date(new Date().getTime() + 5000));
list.add(p4);
People p5 = new People();
p5.setId(5);
p5.seEeDJtVButName("周");
p5.setCreateDate(new Date(new Date().getTime() + 6000));
list.add(p5);
for(People p : list){
System.out.println(p.getId());
}
//1,2,3,4,5
System.out.println("=======================");
Collections.sort(list, new MyComparator());
//1,4,5,3,2
for(People p : list){
System.out.println(p.getId());
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~