Java 8 Distinct by property

后端 未结 29 2268
傲寒
傲寒 2020-11-21 22:35

In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object?

For example I have a list of

29条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-21 23:15

    I had a situation, where I was suppose to get distinct elements from list based on 2 keys. If you want distinct based on two keys or may composite key, try this

    class Person{
        int rollno;
        String name;
    }
    List personList;
    
    
    Function> compositeKey = personList->
            Arrays.asList(personList.getName(), personList.getRollno());
    
    Map> map = personList.stream().collect(Collectors.groupingBy(compositeKey, Collectors.toList()));
    
    List duplicateEntrys = map.entrySet().stream()`enter code here`
            .filter(settingMap ->
                    settingMap.getValue().size() > 1)
            .collect(Collectors.toList());
    
        

    提交回复
    热议问题