Java combine two list

Java 8: Merging two Lists containing objects by key

servers1 contains servers with a name and an attribute1 (but no attribute2 ).
servers2 contains servers with a name and an attribute2 (but no attribute1 ).

public class Server < private String name; private String attribute1; private String attribute2; public Server(String name) < this.name = name; this.attribute1 = ""; this.attribute2 = ""; >//Getters & Setters > 

Does anyone know how I can merge these two lists to one list containing each Server only once (by name ) but with both attributes? There are servers which only exist in one or the other list. The final list should contain all servers.

 List servers1 = new ArrayList<>(); Server s1 = new Server("MyServer"); s1.setAttribute1("Attribute1"); Server s2 = new Server("MyServer2"); s2.setAttribute1("Attribute1.2"); servers1.add(s1); servers1.add(s2); List servers2 = new ArrayList<>(); Server s3 = new Server("MyServer"); s3.setAttribute2("Attribute2"); Server s4 = new Server("MyServer3"); s4.setAttribute2("Attribute2.2"); servers2.add(s3); servers2.add(s4); 

should result in: [Server [name=MyServer, attribute1=Attribute1, attribute2=Attribute2], Server [name=MyServer2, attribute1=Attribute1.2, attribute2=]] Server [name=MyServer3, attribute1=, attribute2=Attribute2.2]] //SOLUTION (thx everybody for the help!)

Map serverMap1 = Stream.concat(servers1.stream(), servers2.stream()) .collect(Collectors.toMap(Server::getName, Function.identity(), (server1, server2) -> < server1.setAttribute2(server2.getAttribute2()); return server1; >)); 

Источник

How to concat two ArrayLists?

I have two ArrayList s of equal size. List 1 consists of 10 names and list 2 consists of their phone numbers. I want to concat the names and number into one ArrayList . How do I do this?

what exactly do you mean by concat? Build a new list wich has 10 elements containing name and number?

8 Answers 8

You can use .addAll() to add the elements of the second list to the first:

Edit: Based on your clarification above («i want a single String in the new Arraylist which has both name and number.«), you would want to loop through the first list and append the item from the second list to it.

int length = array1.size(); if (length != array2.size()) < // Too many names, or too many numbers // Fail >ArrayList array3 = new ArrayList(length); // Make a new list for (int i = 0; i < length; i++) < // Loop through every name/phone number combo array3.add(array1.get(i) + " " + array2.get(i)); // Concat the two, and add it >
array1 : ["a", "b", "c"] array2 : ["1", "2", "3"] 

You might want to specify the size of array3 . i.e. new ArrayList(array1.size()) . Also it’s size() not length() .

Above iterative solution will not work if the length of the two list are different. Ideally the final list should have all of the contents, even if second list doesn’t have element so empty string can be substituted.

Читайте также:  The java stack trace

add one ArrayList to second ArrayList as:

Arraylist1.addAll(Arraylist2); 

EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:

ArrayList arraylist3=new ArrayList(); arraylist3.addAll(Arraylist1); // add first arraylist arraylist3.addAll(Arraylist2); // add Second arraylist 

The numbers are being displayed after the names, i want the names and numbers beside each other. Can you please help me out.

If you want to do it one line and you do not want to change list1 or list2 you can do it using stream

List list1 = Arrays.asList("London", "Paris"); List list2 = Arrays.asList("Moscow", "Tver"); List list = Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList()); 

for a lightweight list that does not copy the entries, you may use sth like this:

List mergedList = new ConcatList<>(list1, list2); 
public class ConcatList extends AbstractList  < private final Listlist1; private final List list2; public ConcatList(final List list1, final List list2) < this.list1 = list1; this.list2 = list2; >@Override public E get(final int index) < return getList(index).get(getListIndex(index)); >@Override public E set(final int index, final E element) < return getList(index).set(getListIndex(index), element); >@Override public void add(final int index, final E element) < getList(index).add(getListIndex(index), element); >@Override public E remove(final int index) < return getList(index).remove(getListIndex(index)); >@Override public int size() < return list1.size() + list2.size(); >@Override public void clear() < list1.clear(); list2.clear(); >private int getListIndex(final int index) < final int size1 = list1.size(); return index >= size1 ? index - size1 : index; > private List getList(final int index) < return index >= list1.size() ? list2 : list1; > > 

Источник

How to Merge Two Lists in Java?

How to Merge Two Lists in Java?

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

How to Merge Two Lists in Java

There are multiple ways we can merge two lists in Java. Let’s explore some of the straightforward ones to get your job done!

1. The addAll() method to merge two lists

The addAll() method is the simplest and most common way to merge two lists. For ArrayList :

import java.util.ArrayList; public class Main  public static void main(String[] args)  ArrayListInteger> l1 = new ArrayListInteger>(); l1.add(1); l1.add(3); l1.add(5); ArrayListInteger> l2 = new ArrayListInteger>(); l2.add(2); l2.add(4); l2.add(6); ArrayListInteger> merge = new ArrayListInteger>(); merge.addAll(l1); merge.addAll(l2); System.out.println("L1 : "+l1); System.out.println("L2 : "+l2); System.out.println("Merged : "+merge); > > 

Merge Arraylists Addall 1

Note the order of appearance of elements matches the order in which addAll() is called. For LinkedLists:

import java.util.LinkedList; public class Main  public static void main(String[] args)  LinkedListInteger> L1 = new LinkedList>(); L1.add(1); L1.add(3); L1.add(5); LinkedListInteger> L2 = new LinkedList>(); L2.add(2); L2.add(4); L2.add(6); LinkedListInteger> merged = new LinkedList>(); merged.addAll(L1); merged.addAll(L2); System.out.println("L1 : "+L1); System.out.println("L2 : "+L2); System.out.println("Merged : "+merged); > > 

LinkedList AddAll 1

2. Using iterators to merge two lists in Java

import java.util.ArrayList; public class Main  public static void main(String[] args)  ArrayListInteger> l1 = new ArrayListInteger>(); l1.add(1); l1.add(3); l1.add(5); ArrayListInteger> l2 = new ArrayListInteger>(); l2.add(2); l2.add(4); l2.add(6); ArrayListInteger> Itmerge = new ArrayList>(); Iterator i = l1.iterator(); while (i.hasNext())  Itmerge.add((int)i.next()); > i=l2.iterator(); while (i.hasNext())  Itmerge.add((int)i.next()); > System.out.println("L1 : "+l1); System.out.println("L2 : "+l2); System.out.println("Merged : "+Itmerge); > > 

Iterator Arraylist 1

Iterator first traverses the ArrayList l1 and adds all the elements to Itmerge, it then traverses the ArrayList l2 and adds all the elements to Itmerge. Another way to merge the two lists is to simply add elements from one list to the other. There is no need to create a new list unless you need to keep the existing data intact.

Iterator i = l1.iterator(); while (i.hasNext())  l2.add((int)i.next()); > System.out.println("Merged : "+l2); 

Single Iter Merge 1

In this case, all the elements are added to the list l2. This saves the memory spent in the creation of an extra list. Adding the elements of one list to another saves the extra traversal. For LinkedList:

import java.util.LinkedList; public class Main  public static void main(String[] args)  LinkedListInteger> L1 = new LinkedList>(); L1.add(1); L1.add(3); L1.add(5); LinkedListInteger> L2 = new LinkedList>(); L2.add(2); L2.add(4); L2.add(6); LinkedListInteger> merged = new LinkedList>(); Iterator i = L1.iterator(); while (i.hasNext())  L2.add((int)i.next()); > System.out.println(L2); > > 

Linkedlist Merge iterator

3. Merge Multiple Lists using for loop

import java.util.ArrayList; public class Main  public static void main(String[] args)  ArrayListInteger> l1 = new ArrayListInteger>(); l1.add(1); l1.add(3); l1.add(5); ArrayListInteger> l2 = new ArrayListInteger>(); l2.add(2); l2.add(4); l2.add(6); ArrayListInteger> Itmerge = new ArrayList>(); for(int i=0;il1.size();i++) Itmerge.add(l1.get(i)); > for(int i=0;il2.size();i++) Itmerge.add(l2.get(i)); > System.out.println(Itmerge); > > 

The loop traverses both the ArrayLists and adds each element one by one to a newly created list. Adding the elements of one list to another saves the extra traversal.

 for(int i=0;il2.size();i++) l1.add(l2.get(i)); > System.out.println(l1); 

Forloop Arraylist 1

This for loop adds the elements of l2 to l1 one by one. In this case, l1 will contain the final list of merged elements. For LinkedList: To understand the traversal of linked lists a little better let us define our own linked list. This will require a class for nodes. A node needs two things, data and the address of the next node. Code for class node :

public class node  int data; node next; public node(int data) this.data=data; next=null; > > 

Note that the next is of type node since it stores the address of a node. Creating the same two lists as used in earlier examples:

public class Main  public static void main(String[] args)  node head = new node(1); node temp = new node(3); head.next=temp; node temp1 = new node(5); temp.next=temp1; node head2 = new node(2); node temp2 = new node(4); head2.next=temp2; node temp3 = new node(6); temp2.next=temp3; > > 

This will create lists that look like : Lists 1Each arrow represents the next link. To link the two lists together we need to link the end of one list to the head of the second. List Merge Graphic 1This can be done as follows:

node trav=head; while(trav.next!=null) trav=trav.next; > trav.next=head2; 

A node ‘trav’ is initiated and pointed at the head of the first list. The first list is traversed until trav reaches the end of the first list. When the end is reached, it changes the next link of the last node to head of the second list. This forms a link between the two lists. Printing all the lists:

public class Main  public static void main(String[] args)  node head = new node(1); node temp = new node(3); head.next=temp; node temp1 = new node(5); temp.next=temp1; node head2 = new node(2); node temp2 = new node(4); head2.next=temp2; node temp3 = new node(6); temp2.next=temp3; //printing list 1 System.out.println("List 1 :"); node trav = head; while(trav!=null) System.out.print(trav.data + " "); trav=trav.next; > System.out.println(); //prinitng list 2 System.out.println("List 2 :"); trav= head2; while(trav!=null) System.out.print(trav.data + " "); trav=trav.next; > System.out.println(); //merging the two list trav=head; while(trav.next!=null) trav=trav.next; > trav.next=head2; // printing merged list System.out.println("merged list :"); trav = head; while(trav!=null) System.out.print(trav.data + " "); trav=trav.next; > > > 

Output Forloop Lists 1

Conclusion

We saw the different ways to merge two lists in Java. These are ranged from inbuilt functions to basic for loops. The last example above gives a deeper understanding of how lists work in Java. Using the approach of the last example you can have more control over the order in which elements appear in the list.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us

Источник

Оцените статью