1.

Java 9 collection Factory Methods

Answer»

Before Java 9, we had to ADD DATA to Set and List separately and then Map them. Java 9 added methods to List, Set and Map along with their overloaded counterparts.

Some of the Collection Objects have the FOLLOWING factory methods:

static <E> List<T> of(T l1, T l2, T l3);   static <E> Set<T>  of(T s1, T s2, T s3); static <K,V> Map<K,V> of(K k1, V v1, K k2, V v2, K k3, V v3); static <K,V> Map<K,V> ofEntries(Map.Entry<? extends K,? extends V>... entries)

The of(...) method is overloaded to have 0-10 parameters and one with variable var args parameter for Set and Map interfaces and is overloaded to have 0-10 parameters for Map interface. When there are more than 10 parameters for a Map Interface, ofEntries() method is used to accept var args parameter.

Let us see an example showing the USE of Collection Factory Methods:

import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class Example {   public static void main(String []args)   {      Set<String> set = Set.of("S", "E", "T");            System.out.println(set);      List<String> list = List.of("L", "I", "S","T");      System.out.println(list);      Map<String, String> map = Map.of("M","m","A","a","P","p");      System.out.println(map);   } }

The output is as FOLLOWS

[S, E , T] [L, I, S, T] {M=m, A=a, P=p


Discussion

No Comment Found