【问题标题】:Functional programming(Streams) return type ArrayList java [duplicate]函数式编程(Streams)返回类型ArrayList java [重复]
【发布时间】:2015-10-24 16:20:49
【问题描述】:

我有一个 List 和另一个 ArrayList。我想区分它们中的每一个并返回新的 ArrayList。

String[] input = scn.nextLine().split("\\s");
ArrayList<String> result = Arrays.stream(input).filter(a -> a.length() > 10).distinct()

我想返回 ArrayList。我返回列表没有问题(Collectors.asList 等......)

问候

【问题讨论】:

    标签: java functional-programming java-8 java-stream


    【解决方案1】:

    您应该通过collect 方法收集结果:

    ArrayList<String> result = Arrays.stream(input)
                                     .filter(a -> a.length() > 10)
                                     .distinct()
                                     .collect(Collectors.toCollection(ArrayList::new));
    

    如果您不关心特定的List 实现,最好使用toList() 收集器:

    List<String> result = Arrays.stream(input)
                                .filter(a -> a.length() > 10)
                                .distinct()
                                .collect(Collectors.toList());
    

    【讨论】:

    • 感谢您的回答!抱歉重复!
    【解决方案2】:

    收集为一个列表,然后从该列表中创建一个新的 ArrayList。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-06-06
      • 2014-06-12
      • 1970-01-01
      • 2017-01-31
      • 2019-05-04
      • 1970-01-01
      • 2015-05-16
      • 1970-01-01
      相关资源
      最近更新 更多