1. Example 1: Creating several programs that containPerson
List of objects and merge them into a new List
In Java, merging Lists of multiple objects usually involves traversing those Lists and adding their elements to a new List. Here, I will give a detailed code example that will show how to merge multiple Lists containing objects of the same type into a single List.
Suppose we have a simplePerson
class, which has two attributes:name
respond in singingage
. We'll create a couple of files containingPerson
List of objects and merge them into a new List.
First, definePerson
Class:
public class Person {
private String name;
private int age;
// constructor method
public Person(String name, int age) {
= name;
= age;
}
// Gettercap (a poem)Setter
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
= age;
}
// toStringmethodologies,Easy to printPersonboyfriend
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Next, write the code to merge the List:
import ;
import ;
public class ListMerger {
public static void main(String[] args) {
// Create threeList,everyoneListContains severalPersonboyfriend
List<Person> list1 = new ArrayList<>();
(new Person("Alice", 30));
(new Person("Bob", 25));
List<Person> list2 = new ArrayList<>();
(new Person("Charlie", 35));
(new Person("David", 40));
List<Person> list3 = new ArrayList<>();
(new Person("Eve", 28));
// Combine theseList
List<Person> mergedList = mergeLists(list1, list2, list3);
// Print the mergedList
(mergedList);
}
// Merge multipleListmethodologies
public static <T> List<T> mergeLists(List<T>... lists) {
List<T> mergedList = new ArrayList<>();
for (List<T> list : lists) {
if (list != null) {
(list);
}
}
return mergedList;
}
}
In this example, we start by defining thePerson
class and provides it with basic constructor methods, Getter and Setter methods, and atoString
method for printing purposes.
Then, in theListMerger
class, we created three classes containingPerson
object's List and use themergeLists
method to merge them.mergeLists
method accepts a variable number of List arguments (via theList<T>... lists
implementation), then iterates over these Lists and uses theaddAll
method adds them to themergedList
in. Note that before adding it, we checked that the List wasnull
, although in this particular example we are not creating thenull
The List.
Finally, we printed the merged List to show the effect of the merge.
This example provides detailed steps to merge a List of multiple objects into a single List, and the code can be run directly with practical reference value and significance.
2. Example Two: Using the Stream API of Java 8
If we are using Java 8 or later, we can utilize the Stream API to merge Lists more succinctly.
import ;
import ;
import ;
import ;
import ;
public class ListMergerStream {
public static void main(String[] args) {
List<Person> list1 = (new Person("Alice", 30), new Person("Bob", 25));
List<Person> list2 = (new Person("Charlie", 35), new Person("David", 40));
List<Person> list3 = (new Person("Eve", 28));
// utilizationStream APIincorporationList
List<Person> mergedList = (list1, list2, list3)
.flatMap(List::stream)
.collect(());
// 打印incorporation后的List
(::println);
}
// suppose that...PersonClasses and other parts are the same as in the previous example
}
In this example, the(list1, list2, list3)
A Stream containing all the Lists is created, and then theflatMap(List::stream)
Convert each List in this Stream into a new Stream and merge these Streams into a single Stream, finally passing thecollect(())
Collect into a new List.
3. Example 3: Using Apache Commons Collections
If we are using the Apache Commons Collections library in our project, we can utilize themethod to merge Lists. but note that the
What is returned is a new collection that contains a view of all the elements of the given collection that are not guaranteed to be unique (unless the elements in the original collection are themselves unique).
However, for List merging, we may need a new List that does contain all the elements, rather than a view. Therefore, we may need to convert the result to a new List. but Apache Commons Collections itself may not have a direct way to do this, so we may still need some extra steps. However, for simple merge operations, we usually use methods from the Java standard library or the Stream API.
But if we do want to use Apache Commons Collections and want a new List with all the elements, we can do that:
import . ;
import ;
import ;
import ;
import ;
public class ListMergerApache {
public static void main(String[] args) {
// Assume list1, list2, list3 are defined and initialized.
// Use CollectionUtils from Apache Commons Collections to merge (but note that this does not directly support merging of Lists)
// A simple way to receive a Collection is to use the ArrayList constructor
List<Person> mergedList = new ArrayList<>((list1, list2, list3));;
// Note: If there are duplicate elements in the list and we want to de-duplicate them, we may need to take an additional step
// Print the merged List
(::println);
}
// Assuming the Person class and other parts are the same as in the previous example
// Note: Available in Apache Commons Collections 4, and it accepts a variable number of Collection parameters.
}
Note, however, that the code example above for thedoes not actually support a variable number of Lists as arguments directly, but rather a variable number of Collections, so the code example above may not be completely technically accurate, as the
s common overloaded methods accept only two Collection arguments. If we need to merge more than two Lists, we may need to call the
union
or use other methods (such as those in the Java Standard Library or the Stream API).
In practice, because the Java standard library already provides powerful and flexible tools (such as the Stream API), there is usually no need to rely additionally on Apache Commons Collections to perform basic collection operations.