Java 8 Distinct by property

后端 未结 29 1837
傲寒
傲寒 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:19

    Here is the example
    public class PayRoll {
    
        private int payRollId;
        private int id;
        private String name;
        private String dept;
        private int salary;
    
    
        public PayRoll(int payRollId, int id, String name, String dept, int salary) {
            super();
            this.payRollId = payRollId;
            this.id = id;
            this.name = name;
            this.dept = dept;
            this.salary = salary;
        }
    } 
    
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Map;
    import java.util.Optional;
    import java.util.stream.Collector;
    import java.util.stream.Collectors;
    
    public class Prac {
        public static void main(String[] args) {
    
            int salary=70000;
            PayRoll payRoll=new PayRoll(1311, 1, "A", "HR", salary);
            PayRoll payRoll2=new PayRoll(1411, 2    , "B", "Technical", salary);
            PayRoll payRoll3=new PayRoll(1511, 1, "C", "HR", salary);
            PayRoll payRoll4=new PayRoll(1611, 1, "D", "Technical", salary);
            PayRoll payRoll5=new PayRoll(711, 3,"E", "Technical", salary);
            PayRoll payRoll6=new PayRoll(1811, 3, "F", "Technical", salary);
            Listlist=new ArrayList();
            list.add(payRoll);
            list.add(payRoll2);
            list.add(payRoll3);
            list.add(payRoll4);
            list.add(payRoll5);
            list.add(payRoll6);
    
    
            Map> k = list.stream().collect(Collectors.groupingBy(p->p.getId()+"|"+p.getDept(),Collectors.maxBy(Comparator.comparingInt(PayRoll::getPayRollId))));
    
    
            k.entrySet().forEach(p->
            {
                if(p.getValue().isPresent())
                {
                    System.out.println(p.getValue().get());
                }
            });
    
    
    
        }
    }
    
    Output:
    
    PayRoll [payRollId=1611, id=1, name=D, dept=Technical, salary=70000]
    PayRoll [payRollId=1811, id=3, name=F, dept=Technical, salary=70000]
    PayRoll [payRollId=1411, id=2, name=B, dept=Technical, salary=70000]
    PayRoll [payRollId=1511, id=1, name=C, dept=HR, salary=70000]
    

提交回复
热议问题