Conditions: do not modifiy the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version.
Is there a simpler way than:
public static <T> List<T> merge(List<T>... args) {
final List<T> result = new ArrayList<>();
for (List<T> list : args) {
result.addAll(list);
}
return result;
}
We can join 2 lists using java8 with 2 approaches.
List<String> list1 = Arrays.asList("S", "T");
List<String> list2 = Arrays.asList("U", "V");
1) Using concat :
List<String> collect2 = Stream.concat(list1.stream(), list2.stream()).collect(toList());
System.out.println("collect2 = " + collect2); // collect2 = [S, T, U, V]
2) Using flatMap :
List<String> collect3 = Stream.of(list1, list2).flatMap(Collection::stream).collect(toList());
System.out.println("collect3 = " + collect3); // collect3 = [S, T, U, V]
The smartest in my opinion:
/**
* @param smallLists
* @return one big list containing all elements of the small ones, in the same order.
*/
public static <E> List<E> concatenate (final List<E> ... smallLists)
{
final ArrayList<E> bigList = new ArrayList<E>();
for (final List<E> list: smallLists)
{
bigList.addAll(list);
}
return bigList;
}
another one liner solution using Java8
stream, since flatMap
solution is already posted, here is a solution without flatMap
List<E> li = lol.stream().collect(ArrayList::new, List::addAll, List::addAll);
or
List<E> ints = Stream.of(list1, list2).collect(ArrayList::new, List::addAll, List::addAll);
code
List<List<Integer>> lol = Arrays.asList(Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6));
List<Integer> li = lol.stream().collect(ArrayList::new, List::addAll, List::addAll);
System.out.println(lol);
System.out.println(li);
output
[[1, 2, 3], [4, 5, 6]]
[1, 2, 3, 4, 5, 6]
Another Java 8 one-liner:
List<String> newList = Stream.of(listOne, listTwo)
.flatMap(Collection::stream)
.collect(Collectors.toList());
As a bonus, since Stream.of()
is variadic, you may concatenate as many lists as you like.
List<String> newList = Stream.of(listOne, listTwo, listThree)
.flatMap(Collection::stream)
.collect(Collectors.toList());
Not simpler, but without resizing overhead:
List<String> newList = new ArrayList<>(listOne.size() + listTwo.size());
newList.addAll(listOne);
newList.addAll(listTwo);