【问题标题】:Convert Map<List> to List<NewType> with new java 8 streams使用新的 java 8 流将 Map<List> 转换为 List<NewType>
【发布时间】:2016-11-02 15:06:14
【问题描述】:

我需要帮助使用 java 8 流 API 进行转换

Map<String, List<Entry<Parameter, String>>> inputData

List<TestSession> testList

使用以下测试会话

private static class TestSession {
    final String mServiceName;
    final Parameter mParam;
    final String mData;
    public TestSession(
        final String aServiceName,
        final Parameter aParameter,
        final String aData) {
        mServiceName = aServiceName;
        mParam = aParam,
        mData= aData;
    }
}

enum Parameter {
    Foo,
    Bar,
    Baz
}

假设输入数据包含以下内容

{"ABC", {{Parameter.Foo, "hello"},{Parameter.Bar, "bye"} }
{"DEF", {{Parameter.Baz, "hello1"},{Parameter.Foo, "bye1"} }

我希望 testList 包含

{
   TestSession("ABC", Parameter.Foo, "hello"), 
   TestSession("ABC", Parameter.Bar, "bye"), 
   TestSession("DEF", Parameter.Baz, "hello1"),
   TestSession("DEF", Parameter.Foo, "bye1")
}

这个想法是每个TestSession 都是使用来自列表中每个条目的inputDataEntry&lt;Parameter, String&gt; 中的密钥构造的。

【问题讨论】:

  • 你已经尝试过什么?什么不起作用?使用flatMapmap 可以轻松解决您的问题
  • @Holger 今天早上我看到了句子结尾的错误,我修复了它以改善问题,这是否决票的原因吗?
  • @johnco3:我没有投反对票,所以我只能猜测。最有可能的是,反对者认为您在尝试自己解决问题时没有付出足够的努力。
  • @Holger 感谢您的意见,顺便说一句,我会在几分钟内尝试您建议的答案

标签: collections java-8 java-stream


【解决方案1】:

假设 TestSession 类被相应地调整为还包含一个 Parameter 字段,您可以执行以下操作:

List<TestSession> result = inputData.entrySet().stream()
    .collect(
      ArrayList::new,
      (list, e1) -> e1.getValue().forEach((e2) ->
        list.add(new TestSession(e1.getKey(), e2.getKey(), e2.getValue()))),
      ArrayList::addAll);

【讨论】:

    【解决方案2】:

    正如comment by the user “soon” 中已经提到的,这个问题可以通过flatMapmap 轻松解决:

    List<TestSession> list = mapList.entrySet().stream()
        .flatMap(e1 -> e1.getValue().stream()
            .map(e2 -> new TestSession(e1.getKey(), e2.getKey(), e2.getValue())))
        .collect(Collectors.toList());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 1970-01-01
      • 2019-01-23
      • 2015-03-20
      相关资源
      最近更新 更多