Check whether list of custom objects have same value for a property in Java 8

前端 未结 5 895
逝去的感伤
逝去的感伤 2020-12-16 13:29

I am new to Java 8. I have a list of custom objects of type A, where A is like below:

 class A {
      int id;
      String name;
 }

I woul

相关标签:
5条回答
  • 2020-12-16 13:54

    another way is to calculate count of distinct names using

    boolean result = myList.stream().map(A::getName).distinct().count() == 1;
    

    of course you need to add getter for 'name' field

    0 讨论(0)
  • 2020-12-16 13:57

    You can map from A --> String , apply the distinct intermediate operation, utilise limit(2) to enable optimisation where possible and then check if count is less than or equal to 1 in which case all objects have the same name and if not then they do not all have the same name.

    boolean result = myList.stream()
                           .map(A::getName)
                           .distinct()
                           .limit(2)
                           .count() <= 1;
    

    With the example shown above, we leverage the limit(2) operation so that we stop as soon as we find two distinct object names.

    0 讨论(0)
  • 2020-12-16 14:01

    One way is to get the name of the first list and call allMatch and check against that.

    String firstName = yourListOfAs.get(0).name;
    boolean allSameName = yourListOfAs.stream().allMatch(x -> x.name.equals(firstName));
    
    0 讨论(0)
  • 2020-12-16 14:03

    Or use groupingBy then check entrySet size.

    boolean b  = list.stream()
                 .collect(Collectors.groupingBy(A::getName, 
                 Collectors.toList())).entrySet().size() == 1;
    
    0 讨论(0)
  • One more option by using Partitioning. Partitioning is a special kind of grouping, in which the resultant map contains at most two different groups – one for true and one for false.

    by this, You can get number of matching and not matching

    String firstName = yourListOfAs.get(0).name;
    
    Map<Boolean, List<Employee>> partitioned =  employees.stream().collect(partitioningBy(e -> e.name==firstName));
    

    Java 9 using takeWhile takewhile will take all the values until the predicate returns false. this is similar to break statement in while loop

    String firstName = yourListOfAs.get(0).name;        
    
            List<Employee> filterList =  employees.stream()
                                                   .takeWhile(e->firstName.equals(e.name)).collect(Collectors.toList());
            if(filterList.size()==list.size())
            {
                //all objects have same values 
            }
    
    0 讨论(0)
提交回复
热议问题