我正在尝试使用Java8新的lambda表达式将List<Map<String, Object>>
过滤和缩减为List<String>
,方法如下:
List<Map<String, Object>> myObjects = new ArrayList<>();
myObjects.stream()
.filter(myObject-> myObject.get("some integer value").equals(expectedValue))
// myObject.get("some attribute") == ["some string", "maybe another string"]
.map(myObject-> myObject.get("some attribute"))
.collect(Collectors.toList());
结果是一个列表,但我想将数组中的所有字符串组合成结果
List<String>
。为了澄清,这是我现在得到的结果:
ArrayList{["some string"], ["another string"]}
但我想要这个:
ArrayList{"some string", "another string"}
有人能给我提示,我需要在哪个部分将String[]
减少为String
吗? 我猜测应该在.map()
的部分,但我不知道该怎么改。
编辑:
这是用于测试目的生成List<Map<String,Object>> myObjects
的方法:
List<Map<String, Object>> myObjects = new ArrayList<>();
Map<String, Object> myObject = new HashMap<>();
myObject.put("some integer value", 1);
String[] theStringIWant = new String[1];
theStringIWant[0] = "Some important information I want";
myObject.put("some attribute", theStringIWant);
myObjects.add(myObject);
它看起来像这样:
List<MyObject{"some attribute": 1}>
注意:这只是我的单元测试的一个示例。列表通常包含多个元素,每个映射都有更多属性,而不仅仅是some attribute
。
.flatmap(myObject-> ((List) myObject.get("list")).stream())
。 - tobias_kjava.lang.ClassCastException:[Ljava.lang.String;无法转换为java.util.List
。 - PeterMap
的List
,每个Map
包含任何类型的值,如果它恰好是一个String
数组,你想把它的所有元素放入结果List
中? - user1983983flatmap(myObject-> Stream.of(myObject.get("list"))
。但是,我不明白你的示例映射如何适用于你的原始代码。"list"
键在哪里? - tobias_k