[英]Flattening a Map<Integer, Map<String, Boolean>> to a List<Boolean>
Using java 8 streams, how do I flatten a Map<Integer, Map<String, Boolean>>
to just a List<Boolean>
so that the final list will contain all the booleans across all values? 使用Java 8流,如何将
Map<Integer, Map<String, Boolean>>
展平为List<Boolean>
以便最终列表将包含所有值中的所有布尔值?
Here is an example of the data: 这是数据示例:
1 -> [{"ABC" -> true}, {"DEF" -> true}]
2 -> [{"DEF" -> false}, {"EFG" -> true}]
3 -> [{"ABC" -> true}, {"DEF" -> false}]
I want to flatten this to a List<Boolean>
so that my list will contain: 我想将其展平为
List<Boolean>
以便我的列表包含:
{true, true, false, true, true, false}
Order is not important. 顺序并不重要。 Content is important.
内容很重要。
Try this: 尝试这个:
Map<Integer, Map<String, Boolean>> map = new HashMap<Integer, Map<String, Boolean>>();
final List<Boolean> collect = map
.values()
.stream()
.flatMap(it -> it.values().stream())
.collect(Collectors.toList());
You can do something like: 您可以执行以下操作:
final Map<Integer, List<Entry>> map = new HashMap<>();
map.put(1, Arrays.asList(new Entry("ABC", true), new Entry("DEF", true)));
map.put(2, Arrays.asList(new Entry("DEF", false), new Entry("EFG", true)));
map.put(3, Arrays.asList(new Entry("ABC", true), new Entry("DEF", false)));
final List<Boolean> booleans = map.entrySet()
.stream()
.flatMap(entry -> entry.getValue().stream())
.map(entry -> entry.value)
.collect(Collectors.toList());
System.out.println(booleans);
But be aware that the order will not be saved here as this is a HashMap
. 但是请注意,由于这是一个
HashMap
,因此不会在此处保存订单。
have a look at the following: 看一下以下内容:
final List<Boolean> collect = map.values().stream() // Stream<Map<String,Boolean>>
.map(Map::values) // Stream<Collection<Boolean>>
.flatMap(Collection::stream) // Stream<Boolean>
.collect(Collectors.toList());
The difference from this and the other answers provided is, that every line only contains one operation (which I personally prefer, its more readable). 与此提供的其他答案的区别在于,每一行仅包含一个操作(我个人更喜欢它的可读性)。
Based on 基于
I want to flatten this to a List so that my list will contain: {true, true, false, true, true, false}
我想将其展平为一个列表,以便我的列表包含:{true,true,false,true,true,false}
the solution could be like this 解决方案可能是这样的
Map<Integer, Map<String, Boolean>> map = new HashMap<>();
map.put(1, new HashMap<String, Boolean>(){{put("ABC", true);put("DEF", true);}});
map.put(2, new HashMap<String, Boolean>(){{put("DEF", false);put("EFG", true);}});
map.put(3, new HashMap<String, Boolean>(){{put("ABC", true);put("DEF", false);}});
System.out.println(map.entrySet().stream().flatMap( t -> t.getValue().values().stream()).collect(Collectors.toList()));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.