Initialize List, Set, Map in java 9 or 10 in one line. 

In this tutorial, let us see that how to initialize List, Set, Map in java 9 or 10 in single line. Until Java 8, there was  no direct way to initialize Java collections (i.e List, Set, Map etc..) in one line. Java 9 has solved the problem and provides a static factory method “of”  which is used to create instance of collections, initialize with values in a single line and also makes the collections  immutable.
In old versions of Java,  one way of initializing  list, Set, Map is as given below
In List 
  List<String> transports = new ArrayList<>(Arrays.asList(“Train”, “Bus”, “Car”, “Bike”, “Bicycle”));
In Set
  Set<String> homeAppliances = new HashSet<>(Arrays.asList(“Microwave oven”, “Washing machine”, “Refrigerator”, “Vacuum cleaner”));
In Map
private static final Map<String, String> cDList;
    static
    {
        cDList = new HashMap<String, String>();
        cDList.put(“1”, “North (N)”);
        cDList.put(“2”, “East (E)”);
        cDList.put(“3”, “South (S)”);
        cDList.put(“4”, “West (W)”);
       }
But in Java 9, List, Set, Map can be initialized easily with predefined values using the new static factory method “of”  in a single line. Example is given  as given below
    List<String> qualifications = List.of(“BE”, “B.Tech”, “MCA”, “MBA”, “M.Sc”, “BCA”);
    Set<String> transports = Set.of(“Train”, “Bus”, “Car”, “Bike”, “Bicycle”);
    Map<Integer,String> mobileBrands = Map.of({1,”Samsung”}, {2,”Apple”}, {3,”Nokia”},                                                                                     {4,”Sony”,{5,”LG”},{6,”HTC”},{7,”Motorola”} );
Here map can be initialized with maximum of 10  elements
The sample java 9 program for collections with predefined data is given below

Output of the above program

listExampleJava9= [Microwave oven, Washing machine, Refrigerator, Vacuum cleaner]
setExampleJava9= [Bus, Train, Bicycle, Bike, Car]
mapExampleJava9= {4=West (W), 3=South (S), 2=East (E), 1=North (N)}

 

Source: Java 9 Collections

You may also like

Leave a Reply