我有一个嵌套的地图形式
TreeMap<LocalDate, Map<Long,TreeMap<BigDecimal,String>>>
我必须处理此地图,最后得到与嵌套TreeMap具有相同结构的地图
TreeMap<BigDecimal, String>>
正好有两个元素。
我可以找到想要的元素
values.entrySet().stream().flatMap(date -> date.getValue().entrySet().stream()
.map(type -> type.getValue().entrySet()))
.filter(valueMap -> valueMap.size() == 2 )
但是我不知道如何表达.collect()来重新组装结构。任何指针都将受到欢迎。
最佳答案
调用flatMap
和map
时,您将丢失信息。您需要保留密钥,以便能够重建您的结构。
稍作更改,您就可以过滤内部地图并使用内部流收集它们,而不会影响外部流的结构:
Map<LocalDate, Map<Long, TreeMap<BigDecimal, String>>> result = values.entrySet().stream()
.collect(
Collectors.toMap(
Entry::getKey,
entry -> entry.getValue()
.entrySet()
.stream()
.filter(subEntry -> subEntry.getValue().size() == 2)
.collect(Collectors.toMap(Entry::getKey,
Entry::getValue)))
);