Home > Java > javaTutorial > How Can I Concatenate Two Java Lists Without Modifying the Originals and Using Only the JDK?

How Can I Concatenate Two Java Lists Without Modifying the Originals and Using Only the JDK?

Patricia Arquette
Release: 2024-12-15 06:02:14
Original
480 people have browsed it

How Can I Concatenate Two Java Lists Without Modifying the Originals and Using Only the JDK?

Joining Lists in Java Without Modification or External Libraries

When merging two lists, it's often desirable to avoid modifying the originals while using only the JDK. Here's a comprehensive analysis of various approaches:

Original Method:

As presented in the question, creating a new list, copying elements from both input lists, and adding them to the new list is a straightforward method:

List<String> newList = new ArrayList<>();
newList.addAll(listOne);
newList.addAll(listTwo);
Copy after login

JDK 1.3 Version:

For Java 1.3 compatibility, one can use the Iterator.addAll method:

List<String> newList = new ArrayList<>();
newList.addAll(listOne);
newList.addAll(listTwo.iterator());
Copy after login

Java 8 Stream Concatenation:

In Java 8 and later, Stream concatenation offers a concise and efficient alternative:

List<String> newList = Stream.concat(listOne.stream(), listTwo.stream())
                             .collect(Collectors.toList());
Copy after login

Java 16 toList Method:

Java 16 introduces the toList method, which simplifies stream collection:

List<String> newList = Stream.concat(listOne.stream(), listTwo.stream()).toList();
Copy after login

One-Line Solution:

Combining the previous approaches allows for a one-liner:

List<String> newList = new ArrayList<>().addAll(listOne).addAll(listTwo);
Copy after login

Note:

All these methods satisfy the specified conditions of not modifying the original lists, using only the JDK, and not relying on external libraries. The provided solutions range from classic techniques to modern Java features, offering flexibility based on platform compatibility and coding preferences.

The above is the detailed content of How Can I Concatenate Two Java Lists Without Modifying the Originals and Using Only the JDK?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template