djm*_*.im 3 java arrays list java-8
我想创建一个城市名称列表.我知道两种方式.
List<String> cities = Stream.of("Paris", "London", "New York", "Tokyo").collect(Collectors.toList());
List<String> cities = Arrays.asList("Paris", "London", "New York", "Tokyo");
Run Code Online (Sandbox Code Playgroud)
Stream.of(..).collect(..)
和之间有什么区别Arrays.asList(..)
?
Stream.collect()
将返回一个List<>
非固定大小(具有当前实现toList()
)
List<String> cities = Stream.of("Paris", "Tokyo").collect(Collectors.toList());
cities.add("foo"); // OK
Run Code Online (Sandbox Code Playgroud)
在创建基本的情况下List
使用它是无用的Stream
,在需要在收集数据之前进行操作时使用它们,如过滤器,地图,......
Arrays.asList()
将返回List<>
固定大小:see Documentation
List<String> cities = Arrays.asList("Paris", "London", "New York", "Tokyo");
cities.add("bar"); // NOK : java.lang.UnsupportedOperationException
Run Code Online (Sandbox Code Playgroud)
当你快速需要一个List
元素,迭代或其他简单的东西但不再需要时,可以使用它,然后使用List
返回到第1点的实现.
构造.collect(Collectors.toCollection(ArrayList::new));
将保证返回的列表是可变的,因为对toList
返回的List的类型,可变性,可序列化或线程安全性没有保证.