Pet*_*ter 5 java lambda java-8
我试图通过这样做来过滤并减少使用Java8新lambda 的List<Map<String, Object>>to 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());
Run Code Online (Sandbox Code Playgroud)
结果是List,但我想将数组中的所有字符串组合到结果中List<String>.
为了澄清它,这是我现在得到的结果:
ArrayList{["some string"], ["another string"]}
Run Code Online (Sandbox Code Playgroud)
但我想要这个:
ArrayList{"some string", "another string"}
Run Code Online (Sandbox Code Playgroud)
有人可以给我一个提示,我必须将哪一部分减少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);
Run Code Online (Sandbox Code Playgroud)
看起来像这样:
List<MyObject{"some attribute": 1}>
Run Code Online (Sandbox Code Playgroud)
注意:这只是我的unittest的一个例子.列表规范包含多个元素,每个地图都有更多的属性,而不仅仅是some attribute.
您可能需要另一个过滤器,但这就是我的制作方法:
public static void main(String[] args) {
List<Map<String, Object>> myObjects = new ArrayList<>();
Map<String, Object> myObject1 = new HashMap<>();
myObject1.put("some attribute", 1);
myObject1.put("some string", new String[] { "Some important information I want"});
myObjects.add(myObject1);
Map<String, Object> myObject2 = new HashMap<>();
myObject2.put("some attribute", 1);
myObject2.put("some string", new String[] { "hello", "world" });
myObjects.add(myObject2);
Map<String, Object> myObject3 = new HashMap<>();
myObject3.put("some attribute", 2);
myObject3.put("some string", new String[] { "don't", "want", "this"});
myObjects.add(myObject3);
Map<String, Object> myObject4 = new HashMap<>();
myObject4.put("some string", new String[] { "this", "one", "does", "not", "have", "some attribute"});
myObjects.add(myObject4);
List<String> list = myObjects.stream()
.filter(map -> map.containsKey("some attribute"))
.filter(map -> map.get("some attribute").equals(Integer.valueOf(1)))
.flatMap(map -> Arrays.stream((String[])map.get("some string")))
.collect(Collectors.toList());
System.out.println(list);
}
Run Code Online (Sandbox Code Playgroud)
结果是[Some important information I want, hello, world]
| 归档时间: |
|
| 查看次数: |
287 次 |
| 最近记录: |