Wednesday 11 October 2017

Initialize list in one line

In this post, I am going to show you, how to define a list in one line.

In general, we create an instance of ArrayList class and call the add method to add new elements to the array list.
  List<String> countries = new ArrayList<>();

  countries.add("India");
  countries.add("Germany");
  countries.add("Canada");
  countries.add("Singapore");

There are other ways to define array list in one line.
         a. By using Arrays.asList method
         b. By using List.of method
         c. By using Double Brace Initialization
         d. By using streams
         e. By using Collections.singletonList


By using Arrays.asList method
List<String> countries = Arrays.asList("India", "Germany", "Canada", "Singapore");
                                  (or)
String arr[] = {"India", "Germany", "Canada", "Singapore"};
List<String> countries = Arrays.asList(arr);


By using List.of method
From Java9 onwards List interface provides 'of' method to define list.
List<String> strings = List.of("India", "Germany", "Canada", "Singapore");

By using Double Brace Initialization
  List<String> countries = new ArrayList<String>() {
   {
    add("India");
    add("Germany");
    add("Canada");
    add("Singapore");
   }
  };

By using streams
Streams are available from Java8.
List<String> places = Stream.of("India", "Germany", "Canada", "Singapore").collect(Collectors.toList());


By using Collections.singletonList
If your list has only one element, then you can use singletonList.
List<String> country = Collections.singletonList("India");



No comments:

Post a Comment