-3

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.

Kevin Nammour
  • 13
  • 1
  • 4
  • 1
    [`List.of()`](https://docs.oracle.com/javase/9/docs/api/java/util/List.html#of-E...-) is one way, for immutable lists; `Arrays.asList(..)` - is another. – Giorgi Tsiklauri Sep 08 '20 at 19:42
  • 1
    or earlier `Arrays.asList()` – Nowhere Man Sep 08 '20 at 19:43
  • 2
    Does this answer your question? [What is the shortest way to initialize List of strings in java?](https://stackoverflow.com/questions/6520382/what-is-the-shortest-way-to-initialize-list-of-strings-in-java) – Savior Sep 08 '20 at 19:47
  • Or https://stackoverflow.com/questions/1005073/initialization-of-an-arraylist-in-one-line – Savior Sep 08 '20 at 19:47

2 Answers2

0

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);
        }
    };
Giorgi Tsiklauri
  • 9,715
  • 8
  • 45
  • 66
0

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);
Sagar Gangwal
  • 7,544
  • 3
  • 24
  • 38