Home >Java >javaTutorial >How Can I Efficiently Combine Two Java Lists into a New One?

How Can I Efficiently Combine Two Java Lists into a New One?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 06:29:06749browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn