在 Java 中,如何根据类实例的任何属性过滤类实例列表,以在流或一行中获取另一个实例

问题描述 投票:0回答:2

如何使用流或任何其他方式写入一行而不是 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")

java java-stream
2个回答
2
投票

您可以使用 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);

0
投票

List<...> newList = objectList.stream() .filter(obj -> otherListOrSet.stream().anyMatch(其他 -> other.getIntValue.equals(obj.getIntValue))) .toList();

© www.soinside.com 2019 - 2024. All rights reserved.