Merge two list into a single list - java

I have a ArrayList as below.
ArrayList<ArrayList<String>> a = new ArrayList<ArrayList<String>>();
Where ArrayList 'a' contains two ArrayList of string as below.
[a,b,c,d] & [1,2,3,4]
How to merge these two list into a single list as below.
[a,b,c,d,1,2,3,4]
Thanks In Advance.

You combine a foreach loop and the addAll method.
Example
ArrayList<String> combined = new ArrayList<String>();
for(ArrayList<String> list : a) {
combined.addAll(list);
}
How this works?
A for each loop will traverse through every member of a Collection. It has a temporary variable, in this case list that it assigns the current element too. All you're doing is adding every element inside each value for list, to one ArrayList named combined.

Just iterate through all the inner lists of a using foreach loop and addAll to result arraylist
ArrayList<String> merged = new ArrayList<String>();
for(ArrayList<String> list : a){
merged.addAll(list);
}
EDIT:
As #Lubo pointed out.
Note that this way you can end up with many arrays being created and thrown away internally in ArrayList. If you have large lists (number of contained elements), consider looking here: Union List

This should work
ArrayList<ArrayList<String>> a = new ArrayList<ArrayList<String>>();
List<String> result = new ArrayList<String>();
for (ArrayList<String> arrayList : a) {
result.addAll(arrayList);
}
Look into main loop and get each list in it and add to your result list.

We have some other ways too, If you can use Apache commons-collection
ListUtils.union(java.util.List list1, java.util.List list2)
Returns a new list containing the second list appended to the first list.

Use ArrayList.addAll(). Something like this should work (assuming lists contain String objects; you should change accordingly).
List<String> combined = new ArrayList<String>();
combined.addAll(firstArrayList);

If you need an Iterable, you can use Guava:
Iterables.concat(Iterable<? extends Iterable<? extends T>> inputs)
And if you really need a List, you can cast a resulting Iterable to a List using this:
Lists.newArrayList(Iterable<? extends E> elements)
or
Lists.newLinkedList(Iterable<? extends E> elements)

Java 8 streams provide another solution:
List<List<String>> list = Arrays.asList(
Arrays.asList("1", "2"),
Arrays.asList("3", "4"),
Arrays.asList("5", "6")
);
List<String> merged = list
.stream()
.reduce(new ArrayList<>(),(accumulator, sublist) -> {accumulator.addAll(sublist);return accumulator;});
System.out.println(merged);
It is similar to the accepted answer: you loop through your list (using Stream.reduce) to add all of your sublists elements to your merged list.

List<Integer> one = Arrays.asList(1, 2,3);
List<Integer> two = Arrays.asList(4, 5,6);
List<Integer> out = Stream.of(one, two)
.collect(ArrayList::new, (listStream, item) -> listStream.addAll(item), (item1, item2) -> {});
System.out.println(out);

Merging lists without loop with Guava
Using FluentIterable.transformAndConcat.
Applies function to each element of this fluent iterable and returns a fluent iterable with the concatenated combination of results. function returns an Iterable of results.
Usage
List<String> combined = FluentIterable.from(a)
.transformAndConcat(Functions.identity())
.toList();

Related

Java- How can I add a list of objects to another list of Objects

Scenario: got two lists as following:
List<Object[]> listOne = null;
List<Object[]> listTwo = null;
aMethod (see at the bottom) is invoked on each lists which returns a compatible type list
listOne = aMethod(arg1, arg2, arg3);
listTwo = aMethod(argx, argy, argz);
When i try
listOne.add(listTwo);
I get error about the add function . Recommends to use addAll(), which i cant use for my reasons. So, any one have idea how to add a list of objects [] to another list of objects []? Thanks.
public List<Object[]> aMethod(a1, a2, a3) {
List<Object[]> aList = service.getSomeinfo();
return aList;
}
If you do not want to use addAll() method then #Shubbi you can add the second list of object array through the iteration like this :
for(Object[] o:listTwo){
listOne.add(o);
}
There is another way and is very efficient also by using Stream Api if you are using Java 8 or upper version
listOne = Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
Use Stream
listOne = Stream.concat(listOne.stream(), listTwo.stream())
.collect(Collectors.toList());
https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
You can use addAll function of list which adds all the elements of one array to other.
listOne.addAll(listTwo);
listOne will contain elements from both the lists.
You could add both list to third list as:
List<Object[]> listThree = new ArrayList<Object[]>(listOne);
listThree.addAll(listTwo);
Refer: https://docs.oracle.com/javase/8/docs/api/java/util/List.html#addAll-java.util.Collection-

Is there a way to filter out the elements of a List containing object having a String element based on another List of String

I have a List of an object List<Object> which Objects contains String elements . Now There is also another List of String List<String> .
I want the first List to only contain objects which are elements of the second list.
What is the most efficient way to do this?
You can use the contains() method of the list and that's convenient in your case since it will equals() check the Strings.
e.g.
List<String> otherList = new ArrayList<>();
List<Object> test = new ArrayList<>();
Iterator<Object> it = test.iterator();
while(it.hasNext()){
if(!otherList.contains(it.next().getString())) it.remove();
}
or in Java8 streams
test.stream().filter(e -> otherList.contains(e.getString()))
.collect(Collectors.toList());
This will generate you a new List.

Comparing string ArrayList

I have 2 array list that contain strings:
List1 = [no, yes, ok, not]
List2 = [no, but, vote, check]
Now, how do I compare List1 with List2 and remove the words in List1 if the same word are found in List2. The sorted word(without the same word) are stored in another arraylist.
Outcome should be like this:
List3 = [yes, ok, not]
If you want to store the result in a new list, you need to clone List1 first:
ArrayList list3 = (ArrayList) list1.clone();
or
ArrayList list3 = new ArrayList(list1);
Then use removeAll:
list3.removeAll(list2);
ArrayList provides method to remove all object present in another list.
Refer Removing elements present in collection
In your case list1.removeAll(list2) should solve your problem
You can create third list , add to it your two lists and find in it third list same words. When you find them , delete one.So you'll check your third list with equals().
I suppose you didn't know about the removeAll(Collection c) method present for ArrayLists or just want another way of doing it.
Since you mention that you need to remove the duplicated words from list1, initialize a HashSet and add all the values in list2 to the Set, like so,
Set<String> set = new HashSet<String>();
for(String s: list2)
set.add(s);
Now, do the same with a clone of list1, taking care to remove the strings from list1.
String[] list3 = new String[list1.size()];
list1.toArray(list3);
for(String s: list3)
if(!set.add(s))
list1.remove(s);
This is done in O(n) time, but takes some auxiliary storage. Please let me know if this solved your problem.

Linked List of Linked Lists in Java

I would like to know how to create a linked list of linked lists. Also, It would be helpful if the predefined LinkedList (class from Java) and its methods are used for defining and for other add, get, listIterating operations.
You can put any object in a list, including another list.
LinkedList<LinkedList<YourClass>> list = new LinkedList<LinkedList<YourClass>>();
is a LinkedList of LinkedLists of YourClass objects. It can also be written in a simplified way since Java 7:
LinkedList<LinkedList<YourClass>> list = new LinkedList<>();
Very simple examples of manipulating such a list:
You then need to create each sublist, here adding a single sublist:
list.add(new LinkedList<YourClass>());
Then create the content objects:
list.get(sublistIndex).add(new YourClass());
You can then iterate over it like this (sublists' items are grouped by sublist):
for(LinkedList<YourClass> sublist : list) {
for(YourClass o : sublist) {
// your code here
}
}
If you want to add specific methods to this list of lists, you can create a subclass of LinkedList (or List, or any other List subclasses) or you can create a class with the list of lists as a field and add methods there to manipulate the list.
Well i've done this code and i've got it right
java.util.LinkedList mainlist = new java.util.LinkedList();
java.util.LinkedList sublist1 = new java.util.LinkedList();
sublist1.add(object1);
sublist1.add(object2);
sublist1.add(object3);
java.util.LinkedList sublist2=new java.util.LinkedList();
sublist2.add(1);
sublist2.add(2);
mainlist.add(sublist1);
mainlist.add(sublist2);
// To retrieve the sublist1 from mainlist...........
java.util.LinkedList temp = (java.util.LinkedList)mainlist.get(0);
Here variable mainlist is LinkedList of LinkedLists and variable temp contains the value the first list stored i.e sublist1..
You can even simplify access to the secondary lists, e.g. using
final List<List<String>> lists = new LinkedList<List<String>>() {
#Override
public List<String> get(final int index) {
while (index >= size()) {
add(new LinkedList<>());
}
return super.get(index);
}
};
This code automatically adds new LinkedLists to the outer list. With this code you can later easily add single values:
lists.get(2).add("Foo");
LinkedList<LinkedList<YourClass>> yourList = new LinkedList<LinkedList<YourClass>>();
As the declaration. To add another linked list (to the end by default) you would do
yourList.add(new LinkedList<YourClass>());
To add an element to lets say the second linked list in the series:
yourList.get(1).add(new YourClass());

Merge 3 arraylist to one

I want to merge down 3 arraylist in one in java. Does anyone know which is the best way to do such a thing?
Use ArrayList.addAll(). Something like this should work (assuming lists contain String objects; you should change accordingly).
List<String> combined = new ArrayList<String>();
combined.addAll(firstArrayList);
combined.addAll(secondArrayList);
combined.addAll(thirdArrayList);
Update
I can see by your comments that you may actually be trying to create a 2D list. If so, code such as the following should work:
List<List<String>> combined2d = new ArrayList<List<String>>();
combined2d.add(firstArrayList);
combined2d.add(secondArrayList);
combined2d.add(thirdArrayList);
What about using java.util.Arrays.asList to simplify merging?
List<String> one = Arrays.asList("one","two","three");
List<String> two = Arrays.asList("four","five","six");
List<String> three = Arrays.asList("seven","eight","nine");
List<List<String>> merged = Arrays.asList(one, two, three);
Using Java 8 Streams:
List of List
List<List<String>> listOfList = Stream.of(list1, list2, list3).collect(Collectors.toList());
List of Strings
List<String> list = Stream.of(list1, list2, list3).flatMap(Collection::stream).collect(Collectors.toList());
Using Java 9 List.of static factory method (Warning: this list is immutable and disallows null)
List<List<String>> = List.of​(list1, list2, list3);
Where list1, list2, list3 are of type List<String>

Categories