Home >Java >javaTutorial >How Can I Efficiently Combine Two Java Lists into a New One?
Joining Lists in Java
You have two lists, listOne and listTwo, and you want to combine them into a new list newList without modifying the originals. The current approach using addAll() is straightforward but verbose.
Java 8 Streaming
For a more concise solution, consider using Java 8 streams. The concat() method lets you merge two streams, and collect() can convert the merged stream back into a list:
List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()) .collect(Collectors.toList());
Java 16 List Factory Method
In Java 16 and above, the toList() method can be simplified further:
List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).toList();
The above is the detailed content of How Can I Efficiently Combine Two Java Lists into a New One?. For more information, please follow other related articles on the PHP Chinese website!