Search code examples
javacollectionsvavr

Vavr - turn List of Lists into single List


I've got two vavr Lists:

List<Object> list1 = List.of("one", "two", "three", "for");
List<Object> list2 = List.of("one", "two", List.of("three", "for"));

How can I transform the list2 to be equal to the list1?

EDIT

I try to explain more what I want to achive:

System.out.println("list1: " + list1);
System.out.println("list2: " + list2);

Output:

list1: List(one, two, three, for)
list2: List(one, two, List(three, for))

I want to flattening all inner lists in the list2, so the flattened list should be equal to list1:

System.out.println("flattened: " + flattened);
System.out.println(list1.equals(flattened));

Should return:

flattened: List(one, two, three, for)
true

Solution

  • With Vavr you don't need all the stream/collect boilerplate of the JDK:

    List<Object> result = list2.flatMap(o -> o instanceof List ? ((List) o) : List.of(o));