I want to join several list using Stream API.
I found a useful example at stackoverflow:
List<Integer>list1=Arrays.asList(1,2,3);
List<Integer>list2=Arrays.asList(4,5,6);
List<Integer>list3=Arrays.asList(7,8,9);
List<Integer>list4=Arrays.asList(10,0,-1);
List<Integer> newList =
Stream.of(list1, list2, list3,list4)
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println(newList); // prints [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0, -1]
Nice. But in my case, I can`t determine how many lists to use this Stream.of().
I thought about using varargs at jdk8. like this
public List<Integer> getNewList(List... list) {
List<Integer> newList =
Stream.of(list)
.flatMap(Collection::stream)
.collect(Collectors.toList());
return newList;
}
getNewList(list1, list2, list3, list...)
Unfortunately, it didn`t work well. Is there a way to make this work?