【问题标题】:Stream over a List of Map and collect specific key流过地图列表并收集特定密钥
【发布时间】:2017-06-06 09:20:25
【问题描述】:

这是我的清单:

[
    {name: 'moe', age: 40}, 
    {name: 'larry', age: 50}, 
    {name: 'curly', age: 60}
];

我想像这样提取name 值并创建另一个List

["moe", "larry", "curly"]

我已经编写了这段代码并且它可以工作:

List<String> newList = new ArrayList<>();
for(Map<String, Object> entry : list) {
    newList.add((String) entry.get("name"));
}

但是如何在使用stream 时做到这一点。我试过这段代码不起作用。

List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());

【问题讨论】:

  • 仅供参考,这些不是 json。我刚刚用它们来代表我的List 对象。

标签: java java-8 java-stream


【解决方案1】:

由于您的 List 似乎是 List&lt;Map&lt;String,Object&gt;,因此您的流管道将生成 List&lt;Object&gt;

List<Object> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());

如果你确定你只会得到Strings,你可以将值转换为String

List<String> newList = list.stream().map(x -> (String)x.get("name")).collect(Collectors.toList());

【讨论】:

  • 这看起来像 json 并且有办法将其转换为 String 而不是 Object... 我建议也这样做
【解决方案2】:

x.get("name") 应该被转换为字符串。

例如:

List<String> newList = list.stream().map(x -> (String) x.get("name")).collect(Collectors.toList());

【讨论】:

    【解决方案3】:

    如果您的迭代器中的list 的类型为Map&lt;String, Object&gt;,那么我认为完成该任务的最佳方法就是调用方法keySet(),它将返回Set,但您可以从中创建ArrayList方式如下:

    List<String> result = new ArrayList(list.keySet());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-13
      相关资源
      最近更新 更多