java - Initialisation d'un ArrayList en une ligne

Mots clés : javacollectionsarraylistinitializationjava-9java

meilleur 5 Réponses java - Initialisation d'un ArrayList en une ligne

vote vote

97

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

89

ArrayList<String> list = new ArrayList<String>(); list.add("A"); list.add("B"); list.add("C"); 
ArrayList<String> list = new ArrayList<String>() {{     add("A");     add("B");     add("C"); }}; 
List<String> list = ["A", "B", "C"]; 
vote vote

70

var strings = List.of("foo", "bar", "baz"); 
List<String> strings = List.of("foo", "bar", "baz"); 
List<String> strings = Arrays.asList("foo", "bar", "baz"); 
import static java.util.Arrays.asList;   ... List<String> strings = asList("foo", "bar", "baz"); 
Stream<String> strings = Stream.of("foo", "bar", "baz"); 
Stream<String> strings = Stream.concat(Stream.of("foo", "bar"),                                        Stream.of("baz", "qux")); 
import static java.util.stream.Collectors.toList; ... var strings = Stream.of("foo", "bar", "baz").toList(); // Java 16  List<String> strings = Stream.of("foo", "bar", "baz").collect(toList()); // Java 8 
List<String> strings = new ArrayList<>(List.of("foo", "bar")); strings.add("baz"); 
List<String> strings = new ArrayList<>(asList("foo", "bar")); strings.add("baz"); 
import static java.util.stream.Collectors.toCollection;  List<String> strings = Stream.of("foo", "bar")                              .collect(toCollection(ArrayList::new)); strings.add("baz"); 
// Iterable if you just need iteration, for (String s : strings): void method(Iterable<String> strings) {      for (String s : strings) { ... }  }  // Collection if you also need .size(), .isEmpty(), or .stream(): void method(Collection<String> strings) {     if (!strings.isEmpty()) { strings.stream()... } }  // List if you also need random access, .get(index): void method(List<String> strings) {     strings.get(...) }  // Don't declare a specific list implementation // unless you're sure you need it: void method(ArrayList<String> strings) {     ??? // You don't want to limit yourself to just ArrayList } 
vote vote

63

List<String> strings = new ArrayList<String>(Collections.singletonList("A")); 
List<String> strings = new ArrayList<String>(); Collections.addAll(strings,"A","B","C","D"); 
vote vote

54

ArrayList<String> places = Lists.newArrayList("Buenos Aires", "Córdoba", "La Plata"); 

Questions similaires