您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關如何使用List對象實現去重,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
1、List<Object>去重
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> list = new ArrayList<People>(); 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<People> set = new HashSet<People>(list); list.clear(); list.addAll(new ArrayList<People>(set)); for(People p : list){ System.out.println(p); } }
2、List<Object>按照日期字段排序
自定義Comparator
public class MyComparator implements Comparator<People> { @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> list = new ArrayList<People>(); 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對象實現去重有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。