【问题标题】:RxJava Transforming Map into ListRxJava 将 Map 转换为 List
【发布时间】:2018-10-05 01:52:33
【问题描述】:

这是期望的行为:

[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 比较陌生,所以我想知道是否有最佳实践或类似的东西。

【问题讨论】:

  • 即使没有 Rx,在 Kotlin 中也会更容易:map.flatMap { entry -&gt; (0 until entry.value).map { entry.key } }。但是对于Java,我认为您必须尝试@Niraj Chauhan 的解决方案
  • @AndreyTurkovsky 谢谢安德烈!不幸的是,我现在不能使用 Kotlin。我稍后会在我的角色项目中尝试一下!

标签: rx-java


【解决方案1】:

这个怎么样:

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

【讨论】:

  • 谢谢。它有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 2022-09-30
  • 2021-02-28
相关资源
最近更新 更多