检查自定义对象列表对于 Java 8 中的属性是否具有相同的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48031665/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:55:56  来源:igfitidea点击:

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

javaarraylistjava-8java-stream

提问by Joy

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

我是 Java 8 的新手。我有一个类型 A 的自定义对象列表,其中 A 如下所示:

 class A {
      int id;
      String name;
 }

I would like to determine if all the objects in that list have same name. I can do it by iterating over the list and capturing previous and current value of names. In that context, I found How to count number of custom objects in list which have same value for one of its attribute. But is there any better way to do the same in java 8 using stream?

我想确定该列表中的所有对象是否都具有相同的名称。我可以通过迭代列表并捕获名称的先前和当前值来实现。在这种情况下,我找到了如何计算列表中具有相同属性值的自定义对象的数量。但是有没有更好的方法在 java 8 中使用流来做同样的事情?

采纳答案by Sweeper

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

一种方法是获取第一个列表的名称并调用allMatch并检查它。

String firstName = yourListOfAs.get(0).name;
boolean allSameName = yourListOfAs.stream().allMatch(x -> x.name.equals(firstName));

回答by Ousmane D.

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

您可以mapA--> String应用distinct中间操作,limit(2)在可能的情况下利用启用优化,然后检查是否count小于或等于1在这种情况下所有对象都具有相同的名称,如果不是,则它们不具有相同的名称。

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.

对于上面显示的示例,我们利用该limit(2)操作,以便在找到两个不同的对象名称时立即停止。

回答by Alex M981

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

当然你需要为'name'字段添加getter

回答by Hadi J

Or use groupingBythen check entrySetsize.

或使用groupingBy然后检查entrySet大小。

boolean b  = list.stream()
             .collect(Collectors.groupingBy(A::getName, 
             Collectors.toList())).entrySet().size() == 1;

回答by Niraj Sonawane

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.

使用Partitioning 的另一种选择。分区是一种特殊的分组,其中生成的映射最多包含两个不同的组——一个为真,一个为假。

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 takeWhiletakewhile will take all the values until the predicate returns false. this is similar to break statement in while loop

Java 9 使用 takeWhiletakewhile 将获取所有值,直到谓词返回 false。这类似于 while 循环中的 break 语句

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 
        }