Java 从流中获取唯一对象(如果存在)

Java 从流中获取唯一对象(如果存在),java,java-stream,Java,Java Stream,从具有单个相关属性的bean类开始: @Data class MyBean { private String myProperty; } 现在我得到了一组这些beanset mySet,通常包含0、1或2个元素 问题是:如果所有元素的myProperty都相等,或者为空,那么如何从该集中检索myProperty。最好是在一条线中,作用力为O(n) 我找到了几个例子来确定布尔值是否所有属性都相等。但我想知道相应的属性 还有比这更聪明的吗 String uniqueProperty = m

从具有单个相关属性的bean类开始:

@Data
class MyBean {
    private String myProperty;
}
现在我得到了一组这些bean
set mySet
,通常包含0、1或2个元素

问题是:如果所有元素的
myProperty
都相等,或者为空,那么如何从该集中检索
myProperty
。最好是在一条线中,作用力为O(n)

我找到了几个例子来确定布尔值是否所有属性都相等。但我想知道相应的属性

还有比这更聪明的吗

String uniqueProperty = mySet.stream().map(MyBean::getMyProperty).distinct().count() == 1 
    ? mySet.stream().map(MyBean::getMyProperty).findAny().orElse(null) 
    : null;

您的版本已经是
O(n)

用一行代码就可以做到这一点(尽管您的代码太依赖于您如何编写)


唯一不适用的情况是当所有属性值都为
null
时。您无法区分集合
(null,null)
(null,“A”)
例如,它们都返回
null

,对于这种用例,不使用流的单个迭代看起来更好:

Iterator<MyBean> iterator = mySet.iterator();
String uniqueProperty = iterator.next().getMyProperty();
while (iterator.hasNext()) {
    if (!iterator.next().getMyProperty().equals(uniqueProperty)) {
        uniqueProperty = null; // some default value possibly
        break;
    }
}
Iterator Iterator=mySet.Iterator();
字符串uniqueProperty=iterator.next().getMyProperty();
while(iterator.hasNext()){
如果(!iterator.next().getMyProperty().equals(uniqueProperty)){
uniqueProperty=null;//可能有一些默认值
打破
}
}
首先使用
findAny()
并再次使用
allMatch()
检查
mySet
,以要求所有项目与
过滤器()中的第一个项目相匹配。

这样做的好处是,
allMatch()
仅在必要时计算所有元素()

Iterator<MyBean> iterator = mySet.iterator();
String uniqueProperty = iterator.next().getMyProperty();
while (iterator.hasNext()) {
    if (!iterator.next().getMyProperty().equals(uniqueProperty)) {
        uniqueProperty = null; // some default value possibly
        break;
    }
}
String uniqueProperty = mySet.stream().findAny().map(MyBean::getMyProperty)
        .filter(s -> mySet.stream().map(MyBean::getMyProperty).allMatch(s::equals))
        .orElse(null);