我想创建一个用于测试的选项列表。起初,我这样做:

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

然后,我将代码重构如下:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

有更好的方法吗?


当前回答

有多种方法可以在一行中创建和初始化列表。

    //Using Double brace initialization
    List<String> list1 = new ArrayList<>() {{ add("A");  add("B"); }};
    
    //Immutable List
    List<String> list2 = List.of("A", "B");

    //Fixed size list. Can't add or remove element, though replacing the element is allowed.
    List<String> list3 = Arrays.asList("A", "B");

    //Modifiable list
    List<String> list4 = new ArrayList<>(Arrays.asList("A", "B"));

    //Using Java Stream
    List<String> list5 = Stream.of("A", "B").collect(Collectors.toList());

    //Thread safe List
    List<String> list6 = new CopyOnWriteArrayList<>(Arrays.asList("A", "B"));

其他回答

尝试使用以下代码行:

Collections.singletonList(provider)

最简单的方法:可以使用此方法向任意类型的集合(如ArrayList和HashSet)添加多个元素

ArrayList<String> allViews = new ArrayList<String>();
Collections.addAll(allViews,"hello","world","abc","def","ghi");

对于java-9和更高版本,正如JEP269:集合的便利工厂方法中所建议的,这可以使用集合文本实现,现在使用-

List<String> list = List.of("A", "B", "C");

Set<String> set = Set.of("A", "B", "C");

类似的方法也适用于Map-

Map<String, String> map = Map.of("k1", "v1", "k2", "v2", "k3", "v3")

这与@coobird所述的“收藏文字”提案类似。JEP中也有进一步澄清-


选择

语言更改已被考虑过多次,但均被拒绝:项目硬币提案,2009年3月29日项目硬币提案,2009年3月30日JEP 186关于lambda开发的讨论,2014年1月至3月语言建议被搁置,而不是基于图书馆的建议,因为此消息中总结。

相关:在Java9中重载集合的便利工厂方法有什么意义

集合文本并没有进入Java 8,但可以使用流API在一行中初始化列表:

List<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toList());

如果您需要确保列表是ArrayList:

ArrayList<String> places = Stream.of("Buenos Aires", "Córdoba", "La Plata").collect(Collectors.toCollection(ArrayList::new));

使用Eclipse集合,您可以编写以下内容:

List<String> list = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");

您还可以更具体地了解类型,以及它们是可变的还是不可变的。

MutableList<String> mList = Lists.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableList<String> iList = Lists.immutable.with("Buenos Aires", "Córdoba", "La Plata");

您也可以对套装和包进行同样的操作:

Set<String> set = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableSet<String> mSet = Sets.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet<String> iSet = Sets.immutable.with("Buenos Aires", "Córdoba", "La Plata");

Bag<String> bag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
MutableBag<String> mBag = Bags.mutable.with("Buenos Aires", "Córdoba", "La Plata");
ImmutableBag<String> iBag = Bags.immutable.with("Buenos Aires", "Córdoba", "La Plata");

注意:我是Eclipse集合的提交人。