今天就跟大家聊聊有关如何使用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{ Listlist = new ArrayList (); People p1 = new People(); 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 set = new HashSet (list); list.clear(); list.addAll(new ArrayList (set)); 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{ Listlist = new ArrayList (); 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.setName("周"); 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()); } }
看完上述内容,你们对如何使用List对象实现去重有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注创新互联行业资讯频道,感谢大家的支持。