从List java8中删除重复项

时间:2017-07-31 14:33:14

标签: java-8

我下面有一个类,想要删除包含相同名称的重复者,如何使用Java8 Lambda,预期List包含p1,p3,来自下面。

人:

public class Person {

public int id;
public String name;
public String city;

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 String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

}

测试:

import java.util.ArrayList;
import java.util.List;

public class Testing {

public static void main(String[] args) {

    List<Person> persons = new ArrayList<>();

    Person p1 = new Person();
    p1.setId(1);
    p1.setName("Venkat");
    p1.setCity("Bangalore");
    Person p2 = new Person();

    p2.setId(2);
    p2.setName("Venkat");
    p2.setCity("Bangalore");

    Person p3 = new Person();
    p3.setId(3);
    p3.setName("Kumar");
    p3.setCity("Chennai");

    persons.add(p1);
    persons.add(p2);
    persons.add(p3);

}
}

4 个答案:

答案 0 :(得分:10)

您可以将其过滤掉并生成唯一的Set

Set<Person> set = persons.stream()
            .collect(Collectors.toCollection(() -> 
                 new TreeSet<>(Comparator.comparing(Person::getName))));

甚至更好:

Set<String> namesAlreadySeen = new HashSet<>();

persons.removeIf(p -> !namesAlreadySeen.add(p.getName()));

答案 1 :(得分:8)

List<Person> personsWithoutDuplicates = persons.stream()
 .distinct()
 .collect(Collectors.toList());

答案 2 :(得分:-1)

List modified = pesrons.stream()。collect(Collectors.toCollection(() - &gt; new TreeSet&lt;&gt;(Comparator.comparing(Person :: getName))))。stream()。collect(Collectors。 toList());

这将返回基于名称的非重复列表。

您也可以参考Remove duplicates from a list of objects based on property in Java 8

答案 3 :(得分:-1)

public static void main(String[] args) {

    List<Integer> arrList = Arrays.asList(10, 20, 10, 30, 20, 40, 50, 40);

    arrList.stream().distinct().collect(Collectors.toList()).forEach(System.out::println);

}