Java 8 - 一行代码初始化List Arrays.asList和Stream.of的区别

3
我想创建一个城市名称列表,我知道两种方法。
List<String> cities = Stream.of("Paris", "London", "New York", "Tokyo").collect(Collectors.toList());

List<String> cities = Arrays.asList("Paris", "London", "New York", "Tokyo");
< p> Stream.of(..).collect(..)和Arrays.asList(..)之间有什么区别?


4
"Preferable" 指的是什么? - azro
让我们说得更好。 - djm.im
3
这两种方法编译成Java字节码后是否相同?它们怎么可能相同呢?一种构建一个Stream,对该流进行操作,最后创建一个List。另一种采用一些可变参数并创建一个List。如果它们不同,哪一种更好使用?答案基于个人意见,因此不属于SO的讨论范围。 - Turing85
3
“更好”和“更可取”一样糟糕。更好基于什么? - Jorn Vernee
1个回答

8
  1. Stream.collect() will return a List<> with non-fixed size (with the current implementation of toList())

    List<String> cities = Stream.of("Paris", "Tokyo").collect(Collectors.toList());
    cities.add("foo"); // OK
    

    In the case of create a basic List it's useless to use Stream, use them when you need to make operation before collecting data, like filter, map, ...


  1. Arrays.asList()will return List<> of fixed size : see Documentation

    List<String> cities = Arrays.asList("Paris", "London", "New York", "Tokyo");
    cities.add("bar"); // NOK : java.lang.UnsupportedOperationException
    

    This can be used when you quickly need a List of elements, for iteration, or other simple thing but no more, then use a implementation of List of go back to point 1.


< p >使用 .collect(Collectors.toCollection(ArrayList::new)); 构造函数可以保证返回的列表是可变的,而对于 toList 没有关于返回的列表类型、可变性、可序列化性或线程安全性的保证


2
虽然在当前的JDK版本(8到10)中可以修改Collectors.toList返回的列表,但并没有明确指定它可以被修改。 - Stuart Marks
2
Stream.of("Paris", "Tokyo").collect(Collectors.toCollection(ArrayList::new)); 会保证返回的列表是可变的,而对于 toList 则无法保证返回的 List 的类型、可变性、可序列化性或线程安全性。详见官方文档 - Ousmane D.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接