Merge 3 arraylist to one - java

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>

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-

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.

Merge two list into a single list

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();

Why can't you have a "List<List<String>>" in Java? [duplicate]

This question already has answers here:
Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?
(19 answers)
Closed 5 years ago.
In Java, why doesn't the following line of code work?
List<List<String>> myList = new ArrayList<ArrayList<String>>();
It works if I change it to
List<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
At first, I thought maybe you can't have lists of an interface, but I can create a List<Runnable> just fine.
Ideas?
Generic types are more pedantic.
List means List or any sub-type, but <List> means only List. If you want a sub-type you need to have <? extends List>
I suspect you can use
List<List<String>> myList = new ArrayList<List<String>>();
The reason you can't do this is that you can be using a reference to a reference and with an extra level of indirection you have to be careful.
// with one level of indirection its simple.
ArrayList alist = new ArrayList();
List list = aList; // all good
list = new LinkedList(); // alist is still good.
With generics you can have two level of indirection which can give you problems so they are more pedantic to avoid these issues.
// with two levels of indirection
List<ArrayList> alist = new ArrayList<ArrayList>();
List<List> list = (List) alist; // gives you a warning.
list.add(new LinkedList()); // adding a LinkedList into a list of ArrayList!!
System.out.println(alist.get(0)); // runtime error
prints
Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList
cannot be cast to java.util.ArrayList
Lets start with this:
ArrayList<ArrayList<String>> myList = new ArrayList<ArrayList<String>>();
This is creating an ArrayList whose elements are ArrayLists.
Now suppose we could assign that to
List<List<String>> myList2 = myList.
Now, we should be able to do this:
myList2.add(new LinkedList<String>());
But that means we have added a LinkedList to a list whose elements are supposed to be ArrayLists. Ooops!!!
In reality, the assignment of myList to myList2 is not legal ... and that ensures that it is not possible to add the wrong kind of List<String> to the ArrayList<ArrayList<String>> object. (No Peter, it is not just pedantry :-) )
Only the top level collection can be declared as an implementing class, while the nested ones must remain interfaces until you actually create instances:
List<List<String>> rootList = new ArrayList<List<String>>();
and then when you create an element to go in, you make it an implementation:
List<String> nodeList = new ArrayList<String>();
rootList.add(nodeList);
Its comparing Type from left(declaration) side to Type from right(instantiation) side. In Left, your type is List<String> while in right, it's ArrayList<String>. If complaining about the difference.
Please update the right side(instatiation) as List i.e.
List<List<String>> myList = new ArrayList<List<String>>();
This should work fine.
I know this is an old question but I just wanted to share my idea.
Instead of making a List of Lists, I personally just make a List of Type[] (List<Type[]> listArray = new ArrayList<Type[]>();), I generate a separate List of just Type (List<Type> list = new ArrayList<Type>();), then .add(list.toArray()). This way, it's clearer and easier to read than the List of Lists syntax which is confusing.
For example, in a recent project where I had an input file where each line with only a "0" meant a new line in the original (it was an encryption algorithm):
String[] input = getInputContents(inFile);
List<String> currentBuffer = new ArrayList<String>();
List<String[]> buffers = new ArrayList<String[]>();
for(String line : input) {
if(line.equals("0")) {
buffers.add((String[])currentBuffer.toArray());
currentBuffer = new ArrayList<String>();
} else {
currentBuffer.add(line);
}
}
the list<list<string>> l1=new list<list<string>>(); is allowed if the list contains one more list inside the list.
public final class CPanelXMLBuilder extends PanelXMLBuilder {
public CPanelXMLBuilder(AuthenticatedUser pAuthenticatedUser, Map<String, Object> pSessionMap, Map<String, Object> pRequestMap, String pPanelTemplate) throws Exception {
super(pAuthenticatedUser, pSessionMap, pRequestMap, pPanelTemplate, null);
}
public Map<String, Object> buildXMLDocument(List<List<String>> pDetailsList) {
if (pDetailsList.size() == 1) {
List<String> pCustomerDetail = pDetailsList.get(0);
xmlDocument.getRootElement().getChild("E_SHOW1").setText(pCustomerDetail.get(0));
xmlDocument.getRootElement().getChild("E_SHOW2").setText(pCustomerDetail.get(1));
xmlDocument.getRootElement().getChild("E_SHOW3").setText(pCustomerDetail.get(2));
xmlDocument.getRootElement().getChild("E_SHOW4").setText(pCustomerDetail.get(3));
xmlDocument.getRootElement().getChild("E_SHOW5").setText(pCustomerDetail.get(4));
xmlDocument.getRootElement().getChild("ServerTimestamp").setText(pCustomerDetail.get(5).substring(0, 19));
} else {
xmlDocument.getRootElement().getChild("AlertType").setText("INFO");
xmlDocument.getRootElement().getChild("Alert").setText("There is no matching record.");
}
requestMap.put(RequestMapKeys.XML_DOCUMENT, xmlDocument);
return requestMap;
}
}

How to make a new List in Java

We create a Set as:
Set myset = new HashSet()
How do we create a List in Java?
List myList = new ArrayList();
or with generics (Java 7 or later)
List<MyType> myList = new ArrayList<>();
or with generics (Old java versions)
List<MyType> myList = new ArrayList<MyType>();
Additionally, if you want to create a list that has things in it (though it will be fixed size):
List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");
Let me summarize and add something:
JDK
1. new ArrayList<String>();
2. Arrays.asList("A", "B", "C")
Guava
1. Lists.newArrayList("Mike", "John", "Lesly");
2. Lists.asList("A","B", new String [] {"C", "D"});
Immutable List
1. Collections.unmodifiableList(new ArrayList<String>(Arrays.asList("A","B")));
2. ImmutableList.builder() // Guava
.add("A")
.add("B").build();
3. ImmutableList.of("A", "B"); // Guava
4. ImmutableList.copyOf(Lists.newArrayList("A", "B", "C")); // Guava
Empty immutable List
1. Collections.emptyList();
2. Collections.EMPTY_LIST;
List of Characters
1. Lists.charactersOf("String") // Guava
2. Lists.newArrayList(Splitter.fixedLength(1).split("String")) // Guava
List of Integers
Ints.asList(1,2,3); // Guava
In Java 8
To create a non-empty list of fixed size (operations like add, remove, etc., are not supported):
List<Integer> list = Arrays.asList(1, 2); // but, list.set(...) is supported
To create a non-empty mutable list:
List<Integer> list = new ArrayList<>(Arrays.asList(3, 4));
In Java 9
Using a new List.of(...) static factory methods:
List<Integer> immutableList = List.of(1, 2);
List<Integer> mutableList = new ArrayList<>(List.of(3, 4));
In Java 10
Using the Local Variable Type Inference:
var list1 = List.of(1, 2);
var list2 = new ArrayList<>(List.of(3, 4));
var list3 = new ArrayList<String>();
And follow best practices...
Don't use raw types
Since Java 5, generics have been a part of the language - you should use them:
List<String> list = new ArrayList<>(); // Good, List of String
List list = new ArrayList(); // Bad, don't do that!
Program to interfaces
For example, program to the List interface:
List<Double> list = new ArrayList<>();
Instead of:
ArrayList<Double> list = new ArrayList<>(); // This is a bad idea!
First read this, then read this and this. 9 times out of 10 you'll use one of those two implementations.
In fact, just read Sun's Guide to the Collections framework.
Since Java 7 you have type inference for generic instance creation, so there is no need to duplicate generic parameters on the right hand side of the assignment:
List<String> list = new ArrayList<>();
A fixed-size list can be defined as:
List<String> list = Arrays.asList("foo", "bar");
For immutable lists you can use the Guava library:
List<String> list = ImmutableList.of("foo", "bar");
//simple example creating a list form a string array
String[] myStrings = new String[] {"Elem1","Elem2","Elem3","Elem4","Elem5"};
List mylist = Arrays.asList(myStrings );
//getting an iterator object to browse list items
Iterator itr= mylist.iterator();
System.out.println("Displaying List Elements,");
while(itr.hasNext())
System.out.println(itr.next());
List is just an interface just as Set.
Like HashSet is an implementation of a Set which has certain properties in regards to add / lookup / remove performance, ArrayList is the bare implementation of a List.
If you have a look at the documentation for the respective interfaces you will find "All Known Implementing Classes" and you can decide which one is more suitable for your needs.
Chances are that it's ArrayList.
List is an interface like Set and has ArrayList and LinkedList as general purpose implementations.
We can create List as:
List<String> arrayList = new ArrayList<>();
List<String> linkedList = new LinkedList<>();
We can also create a fixed-size list as:
List<String> list = Arrays.asList("A", "B", "C");
We would almost always be using ArrayList opposed to LinkedList implementation:
LinkedList uses a lot of space for objects and performs badly when we have lots of elements.
Any indexed operation in LinkedList requires O(n) time compared to O(1) in ArrayList.
Check this link for more information.
The list created by Arrays.asList above can not be modified structurally but its elements can still be modified.
Java 8
As per doc, the method Collections.unmodifiableList returns an unmodifiable view of the specified list. We can get it like:
Collections.unmodifiableList(Arrays.asList("A", "B", "C"));
Java 9
In case we are using Java 9 then:
List<String> list = List.of("A", "B");
Java 10
In case we are at Java 10 then the method Collectors.unmodifiableList will return an instance of truly unmodifiable list introduced in Java 9. Check this answer for more info about the difference in Collections.unmodifiableList vs Collectors.unmodifiableList in Java 10.
List list = new ArrayList();
Or with generics
List<String> list = new ArrayList<String>();
You can, of course, replace string with any type of variable, such as Integer, also.
The following are some ways you can create lists.
This will create a list with fixed size, adding/removing elements is not possible, it will throw a java.lang.UnsupportedOperationException if you try to do so.
List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});
List<String> fixedSizeList = Arrays.asList("Male", "Female");
List<String> fixedSizeList = List.of("Male", "Female"); //from java9
The following version is a simple list where you can add/remove any number of elements.
List<String> list = new ArrayList<>();
This is how to create a LinkedList in java, If you need to do frequent insertion/deletion of elements on the list, you should use LinkedList instead of ArrayList
List<String> linkedList = new LinkedList<>();
As declaration of array list in java is like
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
There is numerous way you can create and initialize array list in java.
1) List list = new ArrayList();
2) List<type> myList = new ArrayList<>();
3) List<type> myList = new ArrayList<type>();
4) Using Utility class
List<Integer> list = Arrays.asList(8, 4);
Collections.unmodifiableList(Arrays.asList("a", "b", "c"));
5) Using static factory method
List<Integer> immutableList = List.of(1, 2);
6) Creation and initializing at a time
List<String> fixedSizeList = Arrays.asList(new String[] {"Male", "Female"});
Again you can create different types of list. All has their own characteristics
List a = new ArrayList();
List b = new LinkedList();
List c = new Vector();
List d = new Stack();
List e = new CopyOnWriteArrayList();
One example:
List somelist = new ArrayList();
You can look at the javadoc for List and find all known implementing classes of the List interface that are included with the java api.
Sometimes - but only very rarely - instead of a new ArrayList, you may want a new LinkedList. Start out with ArrayList and if you have performance problems and evidence that the list is the problem, and a lot of adding and deleting to that list - then - not before - switch to a LinkedList and see if things improve. But in the main, stick with ArrayList and all will be fine.
Using Google Collections, you could use the following methods in the Lists class
import com.google.common.collect.Lists;
// ...
List<String> strings = Lists.newArrayList();
List<Integer> integers = Lists.newLinkedList();
There are overloads for varargs initialization and initialising from an Iterable<T>.
The advantage of these methods is that you don't need to specify the generic parameter explicitly as you would with the constructor - the compiler will infer it from the type of the variable.
More options to do the same thing with Java 8, not better, not worse, just different and if you want to do some extra work with the lists, Streams will provide you more alternatives (filter, map, reduce, etc.)
List<String> listA = Stream.of("a", "B", "C").collect(Collectors.toList());
List<Integer> listB = IntStream.range(10, 20).boxed().collect(Collectors.toList());
List<Double> listC = DoubleStream.generate(() -> { return new Random().nextDouble(); }).limit(10).boxed().collect(Collectors.toList());
LinkedList<Integer> listD = Stream.iterate(0, x -> x++).limit(10).collect(Collectors.toCollection(LinkedList::new));
As an option you can use double brace initialization here:
List<String> list = new ArrayList<String>(){
{
add("a");
add("b");
}
};
List<Object> nameOfList = new ArrayList<Object>();
You need to import List and ArrayList.
With Java 9, you are able to do the following to create an immutable List:
List<Integer> immutableList = List.of(1, 2, 3, 4, 5);
List<Integer> mutableList = new ArrayList<>(immutableList);
There are many ways to create a Set and a List. HashSet and ArrayList are just two examples. It is also fairly common to use generics with collections these days. I suggest you have a look at what they are
This is a good introduction for java's builtin collections. http://java.sun.com/javase/6/docs/technotes/guides/collections/overview.html
List arrList = new ArrayList();
Its better you use generics as suggested below:
List<String> arrList = new ArrayList<String>();
arrList.add("one");
Incase you use LinkedList.
List<String> lnkList = new LinkedList<String>();
List can be created in many ways:
1 - Constructor Initialization
List is an interface, and the instances of List can be created in the following ways:
List<Integer> list=new ArrayList<Integer>();
List<Integer> llist=new LinkedList<Integer>();
List<Integer> stack=new Stack<Integer>();
2- Using Arrays.asList()
List<Integer> list=Arrays.asList(1, 2, 3);
3- Using Collections class methods
Empty List
List<Integer> list = Collections.EMPTY_LIST;
OR
List<Integer> list = Collections.emptyList();
Collections.addAll(list = new ArrayList<Integer>(), 1, 2, 3, 4);
Unmodifiable List
List<Integer> list = Collections
.unmodifiableList(Arrays.asList(1, 2, 3));
Singleton List
List<Integer> list = Collections.singletonList(2);
You can find more way from the reference link below.
Reference:
https://www.geeksforgeeks.org/initializing-a-list-in-java/
Using Eclipse Collections you can create a List like this:
List<String> list1 = Lists.mutable.empty();
List<String> list2 = Lists.mutable.of("One", "Two", "Three");
If you want an immutable list:
ImmutableList<String> list3 = Lists.immutable.empty();
ImmutableList<String> list4 = Lists.immutable.of("One", "Two", "Three");
You can avoid auto-boxing by using primitive lists. Here's how you'd create int lists:
MutableIntList list5 = IntLists.mutable.empty();
MutableIntList list6 = IntLists.mutable.of(1, 2, 3);
ImmutableIntList list7 = IntLists.immutable.empty();
ImmutableIntList list8 = IntLists.immutable.of(1, 2, 3);
There are variants for all 8 primitives.
MutableLongList longList = LongLists.mutable.of(1L, 2L, 3L);
MutableCharList charList = CharLists.mutable.of('a', 'b', 'c');
MutableShortList shortList = ShortLists.mutable.of((short) 1, (short) 2, (short) 3);
MutableByteList byteList = ByteLists.mutable.of((byte) 1, (byte) 2, (byte) 3);
MutableBooleanList booleanList = BooleanLists.mutable.of(true, false);
MutableFloatList floatList = FloatLists.mutable.of(1.0f, 2.0f, 3.0f);
MutableDoubleList doubleList = DoubleLists.mutable.of(1.0, 2.0, 3.0);
Note: I am a committer for Eclipse Collections.
Try this:
List<String> messages = Arrays.asList("bla1", "bla2", "bla3");
Or:
List<String> list1 = Lists.mutable.empty(); // Empty
List<String> list2 = Lists.mutable.of("One", "Two", "Three");
If you need a serializable, immutable list with a single entity you can use:
List<String> singList = Collections.singletonList("stackoverlow");

Categories