【问题标题】:How to make a new list with a property of an Map which is in another list如何使用另一个列表中的 Map 属性创建一个新列表
【发布时间】:2018-09-24 11:58:07
【问题描述】:

假设我有一个List<Map<String,Object>>:

[{'id':1,'name':'xyz'},{'id':2,'name':'abc'},{'id':3,'name':'pqr'}]

我需要生成另一个列表,包括上面列表中的名称:

List<String>

避免使用循环,是否可以通过使用java流api来实现?

【问题讨论】:

    标签: java list dictionary java-8 java-stream


    【解决方案1】:
    List<String> names = list.stream()
                             .map(i -> i.get("name").toString())
                             .collect(Collectors.toList());
    

    由于i.get("name").toString() 可能会产生 NPE,因此明智的做法是过滤掉不包含密钥 "name" 的映射:

    List<String> names = list.stream()
                             .filter(i -> i.containsKey("name"))
                             .map(i -> i.get("name").toString())
                             .collect(Collectors.toList());
    

    或

    List<String> names = list.stream()
                             .map(i -> i.get("name"))
                             .filter(Objects::nonNull)
                             .map(Object::toString)
                             .collect(Collectors.toList());
    

    【讨论】:

    • 怎么样i.getOrDefault(i,"other")
    • @HadiJ 那么我们必须从结果中过滤掉"other"s,对吧?
    • 可能是map(i -&gt; i.get("name")).filter(name -&gt; name != null).map(name -&gt; name.toString())为了防止containsKey?
    • 我们不知道我们有什么样的地图。 containsKey 可能很贵。你认为呢?另一方面,可能有一个带有键 "name" 的 etnry,但如果相应的值可能是 null,OP 应该清除(它似乎不是这样)。
    • 我认为这可能不是 containsKey 是错误的,而是使用 containsKey 然后立即使用 get 意味着地图中每个现有键 2 次查找,而您可能只有 1使用get 查找,然后使用!= null。
    猜你喜欢
    • 2012-06-14
    • 1970-01-01
    • 1970-01-01
    • 2020-01-15
    • 1970-01-01
    • 2018-01-31
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多