我想创建一个城市名称列表。我知道两种方法。
List<String> cities = Stream.of("Paris", "London", "New York", "Tokyo").collect(Collectors.toList());
List<String> cities = Arrays.asList("Paris", "London", "New York", "Tokyo");
Stream.of(..).collect(..)
和 Arrays.asList(..)
有什么区别?
最佳答案
Stream.collect()
将返回List<>
具有非固定大小(当前实现toList()
)List<String> cities = Stream.of("Paris", "Tokyo").collect(Collectors.toList()); cities.add("foo"); // OK
在创建基本的情况下
List
用Stream
没用,当您需要在收集数据之前进行操作时使用它们,例如过滤器, map ,...
Arrays.asList()
将返回List<>
固定大小:see Documentation
List<String> cities = Arrays.asList("Paris", "London", "New York", "Tokyo"); cities.add("bar"); // NOK : java.lang.UnsupportedOperationException
这可以在您快速需要一个
List
时使用元素,用于迭代,或其他简单的事情,但仅此而已,然后使用List
的实现回到第 1 点。
施工.collect(Collectors.toCollection(ArrayList::new));
将保证返回的列表是可变的,至于 toList
there are no guarantees on the type, mutability, serializability, or thread-safety of the List returned
关于Java 8 - 在 Arrays.asList 和 Stream.of 之间的一行差异中初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49969525/