我有一个元素列表,想提取字段属性的值。
问题:所有元素都应该具有相同的属性值。
我可以做得比以下更好或更优雅吗?
Set<String> matches = fields.stream().map(f -> f.getField()).collect(Collectors.toSet());
if (matches.size() != 1) throw new IllegalArgumentException("could not match one exact element");
String distrinctVal = matches.iterator().next(); //continue to use the value
这是否可以直接使用流方法,例如使用
reduce
?
最佳答案
您当前的解决方案很好。您也可以尝试这种方式来避免收集。
使用 distinct()
然后 count()
if (fields.stream().map(f -> f.getField()).distinct().count() != 1)
throw new IllegalArgumentException("could not match one exact element");
获取值(value)
String distrinctVal = fields.get(0).getField();
关于java - 如何从流中仅提取一个允许的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62002153/