(轉)java8實現對象列表去重


java8實現列表去重,java8的stream和lambda的使用實例

通過普通的方式也可以達到去重的效果,但是借助java8新特性可以很方便的實現列表去重,測試demo如下

實體類:

public class Person {
    private int id;
    private String name;
    private int age;

    public Person() {
    }

    public Person(int id, String name, int age) {
        this.id = id;

        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

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

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
@Override
public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }

測試:

       List<Person> persons = new ArrayList();
       List<Integer> ids = new ArrayList<>();//用來臨時存儲person的id
       persons.add(new Person(1, "name1", 10));
       persons.add(new Person(2, "name2", 21));
       persons.add(new Person(5, "name5", 55));
       persons.add(new Person(3, "name3", 34));
       persons.add(new Person(1, "name1", 10));

       List<Person> personList = persons.stream().filter(// 過濾去重
               v -> {
                   boolean flag = !ids.contains(v.getId());
                   ids.add(v.getId());
                   return flag;
               }
       ).collect(Collectors.toList());
       System.out.println(personList);

還可以實現條件過濾和列表排序:

//獲取person集合中的所有大於18周歲,並排序
List<Person> personList= new ArrayList();
personList.add(new Person(1, "name1", 10));
personList.add(new Person(2, "name2", 21));
personList.add(new Person(5, "name5", 55));
personList.add(new Person(3, "name3", 34));
personList.add(new Person(4, "name4", 6));
personList.stream()
        .filter(p -> p.getAge() >= 18)//獲取所有18歲以上的用戶
        //.sorted(Comparator.comparing(Person::getAge))//依年紀升序排序
        .sorted(Comparator.comparing(Person::getAge).reversed())//依年紀降序排序
        .collect(Collectors.toList());
System.out.println(personList);

轉自:https://www.jianshu.com/p/63d2db850a8d


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM