【问题标题】:How to retrieve a property of collection as a collection of string using Java Stream api如何使用 Java Stream api 将集合的属性检索为字符串集合
【发布时间】:2018-03-17 07:50:43
【问题描述】:

我有一个类别列表,其中包含许多属性,如代码、名称、描述、超类别、产品列表等。现在我想遍历它并检索每个类别的代码并将其存储在字符串列表中。这就是我用老派的方式做的。我想知道这是否可以通过 Java 8 Streams 以更好、更清洁、更高效的方式完成。

List<Category> categories = categoryService.getCategoriesForProductCode(productCode);
List<String> categoryCodes = new ArrayList<>();

if(CollectionUtils.isNotEmpty(categories)){
     for(Category cat : categories){
        categoryCodes.add(cat.getCode);
     }
}

【问题讨论】:

    标签: collections java-8 java-stream


    【解决方案1】:

    你可以这样做

       categoryCodes  = categories.stream()
                      .map(category->catgory.getCode()) // .map(Category::getCode)
                      .collect(Collectors.toList());
    

    【讨论】:

    • @Hadi,更具体地说,操作.collect(Collectors.toList()); 应更改为.collect(Collectors.toCollection(ArrayList::new));,因为前者不能保证返回的 List 的类型、可变性、可序列化性或线程安全性。只是想提及这一点,因为 OP 在他们的示例代码 sn-p 中执行 List&lt;String&gt; categoryCodes = new ArrayList&lt;&gt;();
    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2018-10-25
    • 2013-01-16
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多