我正在使用非流方式从集合中获取单个元素。
List<MyCustomClass> list = OtherObject.getMyList();
if (list.size() != 1) {
throw new RuntimeException();
}
MyCustomClass customClass = list.get(0);
除了这种多线方法之外,还有其他方法可以通过流来实现这一点吗?
最佳答案
您可以使用reduce(accumulator)
和 orElseThrow(exceptionSupplier)
以确保流恰好产生一个结果。
MyCustomClass customClass = list.stream()
.reduce((a,b) -> { throw new RuntimeException("Too many values present"); })
.orElseThrow(() -> { throw new RuntimeException("No value present"); });
关于Java流从集合中获取单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61151206/