简体   繁体   English

如何在Java 8流API中实现不变性

[英]how to achieve immutability in Java 8 stream api

Consider the following code. 请考虑以下代码。 I read it is important to achieve immutability in the code while dealing with Stream API. 我读到在处理Stream API时在代码中实现不变性非常重要。 How can we get a list of all the item in lower case with immutability? 我们怎样才能获得具有不变性的小写项目列表?

    List<String> stockList = Arrays.asList("GOOG", "AAPL", "MSFT", "INTC");
    List<String> stockList2 = new ArrayList<>();
    stockList.parallelStream()
            .filter(e -> !e.contains("M"))
            .map(String::toLowerCase)
            .map(e -> stockList2.add(e))
            .collect(toList());
   stockList2.forEach(System.out::println);

You shouldn't be using map() to add elements to a List . 您不应该使用map()将元素添加到List map() is supposed to transform a Stream of elements of one type to a Stream of elements of another type. map()应该将一种类型的元素Stream转换为另一种类型的元素Stream

Use the List returned by collect(Collectors.toList()) : 使用collect(Collectors.toList())返回的List collect(Collectors.toList())

List<String> stockList2 = 
    stockList.stream()
             .filter(e -> !e.contains("M"))
             .map(String::toLowerCase)
             .collect(Collectors.toList());
stockList2.forEach(System.out::println);

You are not mutating any objects. 你没有改变任何对象。 The String s are already immutable ( toLowerCase produces a new String if necessary) and the original List ( stockList ) is not mutated by the creation of the output List ( stockList2 ). String已经是不可变的(如果需要, toLowerCase会生成一个新的String )并且原始ListstockList )不会因创建输出ListstockList2 )而发生变异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM