我有一个元素列表,想提取字段属性的值。问题:所有元素都应该具有相同的属性值。
我可以做得比以下更好或更优雅吗?
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
Run Code Online (Sandbox Code Playgroud)
这是否可以直接使用流方法,例如使用reduce?
您当前的解决方案很好。您也可以尝试这种方式来避免收集。
distinct()然后使用count()
if (fields.stream().map(f -> f.getField()).distinct().count() != 1)
throw new IllegalArgumentException("could not match one exact element");
Run Code Online (Sandbox Code Playgroud)
获取价值
String distrinctVal = fields.get(0).getField();
Run Code Online (Sandbox Code Playgroud)