我正在尝试做一件简单的事情,但我有点卡住了。 我有以下内容:
Map<Date, Collection<String>>
因此,对于一个Date
,我有一个字符串列表(不是唯一列表)。
我需要的是将其转换为以下格式:
List<Object<Date,String>>
第一个列表的每个元素可以出现多次
(Ex of my main list: (date1, string1), (date1, string1), (date2, string2), (date2, string3))
我正在尝试使用 java 流来做到这一点,但不是那么明显。
有什么想法吗?
谢谢。
编辑:这是我到目前为止所拥有的
Map<Date, Collection<MyObject>> result = new HashMap<>();
......adding elements to the map...
result.entrySet().stream().
collect(Collectors.toMap(
e -> e.getKey(),
v -> v.getValue().stream().map( p -> aggregateProductService.findProduct(customer.getPublicId(), p, setId)).
filter(Optional::isPresent).
map(Optional::get).
collect(toList())
)
).entrySet().stream().sorted(Map.Entry.comparingByKey()).flatMap(e -> e.getValue().stream().map(s -> Pair.of(e.getKey(), s))).
limit(10).
collect(toList()).stream().
collect(Collectors.groupingBy(Pair::getLeft, Collectors.toList()));
这段代码无法编译。我有以下错误:
Pair::getLeft "non static method cannot be referenced from static context"
最佳答案
如果我理解正确的话:
map.entrySet()
.stream()
.flatmap(e -> e.getValue().stream().map(s -> Pair.of(e.getKey(), s)))
.collect(Collectors.toList());
关于Java 8 分组依据的逆向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46486564/