lq920320/blogs

2018/01/03--java 8中List<Object>根据Object属性去重代码

Opened this issue · 0 comments

import lombok.Data;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;

/**
 * @author liuqian
 */
public class RemoveDuplicates {

  @Test
  public void removeDuplicatesByName() {
    Person person1 = new Person() {{
      setId(1);
      setName("person1");
    }};
    Person person2 = new Person() {{
      setId(2);
      setName("person2");
    }};
    Person person3 = new Person() {{
      setId(3);
      setName("person2");
    }};

    List<Person> personList = new ArrayList<>();
    personList.add(person1);
    personList.add(person2);
    personList.add(person3);
    System.out.println("====================before================");
    for (Person person : personList) {
      System.out.println(person.toString());
    }
    List<Person> unique = personList.stream().collect(
      collectingAndThen(
        toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
    );
    System.out.println("------------------after-------------------");
    for (Person person : unique) {
      System.out.println(person.toString());
    }
  }

  @Data
  private class Person {
    private int id;
    private String name;

    @Override
    public String toString() {
      return "Person: id is " + id + ", name is " + name;
    }
  }
}

输出结果:

====================before================
Person: id is 1, name is person1
Person: id is 2, name is person2
Person: id is 3, name is person2
------------------after-------------------
Person: id is 1, name is person1
Person: id is 2, name is person2