如何使用流或任何其他方式写入一行而不是 for 循环来过滤此内容。
class Attribute {
String name;
String value;
..
//getter-setter
}
.. main
List<Attribute> list = populateAttributes();
for (Attribute attr : list) {
if (attr.name == "some key") {
return attr.value;
}
}
我有兴趣在一行中执行此操作,因为我将从配置中读取该路径,并且我的通用代码将遍历点序列并使用反射调用方法。所以像这样
classpackage.getAttributes...(getValue where attr.getname == "somekey")
您可以使用 Stream.filter() 过滤属性名称与您的键匹配的属性列表,并找到第一个属性:
Optional<Attribute> attributeOptional = list.stream().filter(attr-> "some key".equals(attr.name).findFirst();
编辑:如果你想要属性之外的值,那么你可以使用Optional.map()将找到的属性映射到它的值,如果没有找到,则使用一些默认值,如null。
String value = list
.stream()
.filter(attr-> key.equals(attr.name))
.findFirst()
.map(attribute -> attribute.value)
.orElse(null);
List<...> newList = objectList.stream() .filter(obj -> otherListOrSet.stream().anyMatch(其他 -> other.getIntValue.equals(obj.getIntValue))) .toList();