RxJava将地图转换为列表

时间:2018-10-05 01:52:34

标签: rx-java

这是您期望的行为:

[A: 4, B: 2, C: 3, D: 3] -> [A,A,A,A,B,B,C,C,C,D,D,D]

我写了一些代码来解决这个问题。这是代码:

Map<String, Integer> terms = new HashMap<>();
Stream.of(terms.entrySet())
    .flatMap(entry -> {
        List<String> items = new ArrayList<>();
        for (int i = 0; i < entry.getValue(); i++) {
            items.add(entry.getKey());
        }
        return Stream.of(items);
    })
    .forEach(System.out::println);

有更好的方法吗?我是Rx的新手,所以我想知道是否有最佳实践或类似的方法。

1 个答案:

答案 0 :(得分:2)

如何?

terms.keySet().stream()
    .map(s -> IntStream.range(0, map.get(s))
            .mapToObj(i -> s).collect(Collectors.toList()))
    .flatMap(List::stream)
    .collect(Collectors.toList());
相关问题