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:
You can create your generic Java 8 utility method to concat any number of lists.
@SafeVarargs
public static <T> List<T> concat(List<T>... lists) {
return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());
}
Here is a java 8 solution using two lines:
List<Object> newList = new ArrayList<>();
Stream.of(list1, list2).forEach(newList::addAll);
Be aware that this method should not be used if
newList
is not known and it may already be shared with other threadsnewList
is a parallel stream and access to newList
is not synchronized or threadsafedue to side effect considerations.
Both of the above conditions do not apply for the above case of joining two lists, so this is safe.
Based on this answer to another question.
Probably not simpler, but intriguing and ugly:
List<String> newList = new ArrayList<String>() { { addAll(listOne); addAll(listTwo); } };
Don't use it in production code... ;)
In Java 8 (the other way):
List<?> newList =
Stream.of(list1, list2).flatMap(List::stream).collect(Collectors.toList());
I'm not claiming that it's simple, but you mentioned bonus for one-liners ;-)
Collection mergedList = Collections.list(new sun.misc.CompoundEnumeration(new Enumeration[] {
new Vector(list1).elements(),
new Vector(list2).elements(),
...
}))
Off the top of my head, I can shorten it by one line:
List<String> newList = new ArrayList<String>(listOne);
newList.addAll(listTwo);