I created an list of lists,
List<List<Integer>> list = new ArrayList<List<Integer>>();
list.add({1});
list.add({1,1});
This is not working. Is there any shortcut of instantiating them and then adding them?
Thank you.
I created an list of lists,
List<List<Integer>> list = new ArrayList<List<Integer>>();
list.add({1});
list.add({1,1});
This is not working. Is there any shortcut of instantiating them and then adding them?
Thank you.
Since Java 5, you can initialize your list inline as:
List<Integer> list = Arrays.asList(1,2,3,4,5);
Since Java 8, you can use Stream API as:
List<Integer> list = Stream.of(1,2,3,4,5).collect(Collectors.toList());
Since Java 9, you can create immutable lists as:
List<Integer> list = List.of(1,2,3,4,5);
Finally, you can also use double brace initializer block, as:
List<Integer> list = new ArrayList<>() {
{
add(1);
add(2);
add(3);
add(4);
add(5);
}
};
You can use Java-9 List.of
.
More about List.of
, you will able to get it from here.
List<List<Integer>> list = List.of(List.of(1),List.of(1,1),List.of(1,2,3));
System.out.println(list);