How to resolve nested arraylist output in java - java

As per some condition i add some values(it may single or multiple values) in my Arraylist.
in common method:
List<Object> listsALL.....
listsALL.add(sItems2);
value will return to calling method.
i can access values below way
sItems100.add(String.valueOf(listsALL.get(3)));
output like
sItems100---------------- [[Item 5, Item 7]]
While fetching the value from sItems100 and add into nested list, i'm getting below output
[[Item 1, Item 2, Item 6], [[Item 5, Item 7]]]
but i expect like
[[Item 1, Item 2, Item 6], [Item 5, Item 7]]
How to resolve this, any one can help in this?

Do you want something like this?
List<Object> listsALL = new ArrayList<Object>();
List<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(6);
List<Integer> list2 = new ArrayList<Integer>();
list2.add(5);
list2.add(7);
listAll.add(list1);
listAll.add(list2);

It is not a great idea to keep a List of generic Objects of different types (e.g. List in your case), and to insert both an singular Object and a List in this initial list.
If it is possible, try using a
List<List<Object>>
instead. Don't forget that List is an interface, implemented below by ArrayList class.
ArrayList<ArrayList<String>> aList = new ArrayList<ArrayList<String>>();
ArrayList<String> firstElement = new ArrayList<String>();
firstElement.add("Object1");
ArrayList<String> secondElement = new ArrayList<String>();
secondElement.add("Object2");
secondElement.add("Object3");
aList.add(firstElement);
aList.add(secondElement);
System.out.println(aList.get(0).get(0));
System.out.println(aList.get(1).get(0));
System.out.println(aList.get(1).get(1));
Here you have two similar Lists in the initial aList, one with only one element, one with two elements.
If you want to use both an Object and a List inside your initial list, you might want to check how to use instanceof operator and casting in Java.
if(aList.get(1) instanceof ArrayList){
System.out.println("True");
}
else {
System.out.println("False");
}
Here is the full example of using instanceof:
ArrayList<Object> aList = new ArrayList<Object>();
String firstElement = "Object1";
ArrayList<String> secondElement = new ArrayList<String>();
secondElement.add("Object2");
secondElement.add("Object3");
aList.add(firstElement);
aList.add(secondElement);
for (int i = 0; i < aList.size(); i++){
if (aList.get(i) instanceof String ){
System.out.println( (String) aList.get(i) );
}
if (aList.get(i) instanceof ArrayList){
System.out.println( ((ArrayList<String>)aList.get(i)).get(0) );
}
}
So the initial aList holds two types of Objects in this case, String and ArrayList. When iterating the list, you use instanceof operator to see what type of Object it is, and cast it accordingly.

Related

How to convert a list of object to a list of integer in Java?

I have a inner list of object into a list and I want to convert it in a list of Integer, because I know that its elements are Integer.
List<List<Object>> valuesModel = FCSMs.get(0).getValues();
for (List<Object> innerList : valuesModel) {
//CONVERT LIST OF OBJECT TO LIST OF INTEGER
}
How Can I do?
For a start it's a good practice to double check that you are in fact dealing with a list of type Integer. You may know that the only input is of that type, but anyone in the future working with your code will not (because it is not typed with Integer). After that you can simply "cast" it to type Integer. Some pseudo code on how to do that can be found below:
List<List<Integer>> result = new ArrayList<>();
for (List<Object> innerList : valuesModel) {
List<Integer> integerList = new ArrayList<>();
for (Object object : innerList) {
if (object instanceof Integer) {
integerList.add((Integer) object);
}
}
result.add(integerList);
}
You can do it like this. Since you know that all objects are Integers, no checks are done to avoid ClassCastExceptions.
Stream the list of lists to a stream of lists.
Then flatten those lists into a stream of object.
cast the object to an Integer.
and collect into a List
List<List<Object>> valuesModel = List.of(List.of(1,2,3,4), List.of(5,6,7,8));
List<Integer> integers = valuesModel.stream()
.flatMap(Collection::stream)
.map(ob->(Integer)ob)
.collect(Collectors.toList());
System.out.println(integers);
Prints
[1, 2, 3, 4, 5, 6, 7, 8]

Adding elements from a List to a List of Lists

I trying to write some code in Java - I have two Lists:
List<List<Integer>> listOfLists;
List<Integer> listOfIntegers;
I want to add each of the Integers in listOfIntegers to a new element (List) in listOfLists, then I need to clear listOfIntegers
I tried:
listOfLists.add(listOfIntegers);
listOfIntegers.clear();
but this clears the reference to the List in listOfLists
Thanks to Manuel Silva I came up with what I need:
List<Integer> newList = new ArrayList<>();
for (Integer i : lineIntegersList)
{
newList.add(i);
}
listOfLists.add(newList);
lineIntegersList.clear();
You could do something like this...
ArrayList<ArrayList<String>> listOlists = new ArrayList<ArrayList<String>>();
ArrayList<String> singleList = new ArrayList<String>();
singleList.add("hello");
singleList.add("world");
listOlists.add(singleList);
ArrayList<String> anotherList = new ArrayList<String>();
anotherList.add("this is another list");
listOlists.add(anotherList);
thanks #tster - here you instantiate your "parent list" and as you would know how to do - just create a child list to add to the parent.. :D
for (Integer i: listOfIntegers) {
List<Integer> list = new LinkedList<Integer>();
list.add(i);
listOfLists.add(list);
}
This solution basically adds a new List with one element for each integer in the list of integer to the initial list of list

Substituting in arraylists

I have an hash map, which maps integers to array of ArrayLists. For example, my data structure is the following:
7->((7,5,**4,3,1**),(7,6,4,3,1))
4->((4,2,1),(4,3,1))
Here, 7 is key, and arraylist e.g is (7,5,4,3,1), the array of arraylist in turn is ((7,5,4,3,1),(7,6,4,3,1))
4 is key, and arraylist e.g. is (4,2,1), the array of arraylist in turn is ((4,2,1),(4,3,1))
I wish to substitute the key values (in any given arraylist) and the values following it to create other arraylists, one example of this is given below:
7->((7,5,**4,2,1**),(7,6,4,2,1),(7,5,4,3,1),(7,6,4,3,1))
the thing I am not getting is how to obtain this substitution....to create bigger arraylists
the thing I am not getting is how to obtain this substitution....to create bigger arraylists..i know the datastructure..but want to create arraylists by substitution as given in subsequent example
Is there someway in java programming by which I may achieve this?
I am a novice at Java programming...I thought long about this but could not move it...can someone please help
HashMap<Integer,ArrayList<ArrayList<Integer>>> map;
map = new HashMap<Integer,ArrayList<ArrayList<Integer>>>();
EDIT: I've used 2 lines so that my answer could be more readable.
What actually do you want?
Is bellow code helpful?
Map<Integer, List<List<Integer>>> mapData = new HashMap<Integer, List<List<Integer>>>();
public void fillData(List<List<Integer>> lists)
{
// provide any kind of list of list
// e.g lists = {2,3,5,3}, {4,5,3,2}, {2,4,3}, {6,3,4}
for(List<Integer> list : lists)
{
int mapKey = list.get(0);
if(mapData.get(mapKey) == null)
{
// list of list will be null in first occurence of key(first element of list).
// create list of list and put tat in map.
List<List<Integer>> tempListOfList = new ArrayList<List<Integer>>();
tempListOfList.add(list);
mapData.put(mapKey, tempListOfList);
}
else
{
// from second occurence of same key.
// put list in the list of list of that key.
List<List<Integer>> listOfListInMap = mapData.get(mapKey);
listOfListInMap.add(list);
}
}
}
public List<List<Integer>> getListsByKey(int key)
{
// get list of list by mapKey
return mapData.get(key);
}
HashMap<Integer, ArrayList<ArrayList<Integer>>>.
below should do it:
Map<Integer, ArrayList <ArrayList<Integer>>> map = new hashMap<>();
Consider using a List of Lists and store this as part of a Map data structure. One possible way would be as follows:
Map<Integer,List<List<Integer>>> map = new HashMap<Integer, List<List<Integer>>>();
//How to add
List<List<Integer>> list = map.get(your_key);
if(list == null){ //This should be for the first time you're accessing the map with the key
list = new ArrayList<List<Integer>>();
}
//Create a inner list which will store the list of numbers
ArrayList<Integer> innerList = new ArrayList<Integer>();
innerList.add(integer_values);
//Add inner list to the list of lists
list.add(innerList);
//Finally put the list of list into the map with the key
map.put(your_key, list);
Edit: Assuming you know index of the list where you want to add new elements:
//Adding numbers to the inner list - assume you know the index
List<List<Integer>> list = map.get(key);
if(list == null || list.size() >= index){ //There's no list against the key or the size of the list is less then the index requested
return;
}
//Add new elements to the inner list
List<Integer> innerList = list.get(index);
innerList.add(your_new_int_values);
//Add inner list to the list of lists
list.add(innerList);
//Finally put the list of list into the map with the key
map.put(key, list);
You want to map integers to a list of lists of integers. This can be declared as:
Map<Integer, List<List<Integer>>> map = new HashMap<List<List<Integer>>>();
You can then put instances of ArrayList<List<Integer>> (or any other class that implements List) and for each such list of lists, you can add instances of ArrayList<Integer>.
You can then use the List.subList() method to put selected sublists into other entries in the map.
Say you have a list containing the two lists (7,5,4,3,1) and (7,6,4,3,1) stored under 7 and you want to construct the list of lists that should be stored under the key 4. You can do this:
List<List<Integer>> sevens = map.get(7);
List<List<Integer>> fours = new ArrayList<List<Integer>>();
for (List<Integer> aSevenList : sevens) {
int index = aSevenList.indexOf(4);
if (index >= 0) {
fours.add(aSevenList.subList(index, aSevenList.size()));
}
}
map.put(4, fours);
If you want to substitute one list as part of another, the following code fragment shows how that might be done:
int[] vals = { 7, 6, 5, 4, 3, 2, 1 };
List<Integer> list = new ArrayList<Integer>();
for (int val : vals) list.add(val);
List<Integer> sub = new ArrayList<Integer>();
sub.add(40);
sub.add(30);
sub.add(20);
System.out.println("Original list: " + list);
List<Integer> slice = list.subList(3, vals.length - 1);
slice.clear();
slice.addAll(sub);
System.out.println("Modified list: " + list);
This will generate the following output:
Original list: [7, 6, 5, 4, 3, 2, 1]
Modified list: [7, 6, 5, 40, 30, 20, 1]
Note that changes to a sublist are propagated to the original list.

Common elements in two lists

I have two ArrayList objects with three integers each. I want to find a way to return the common elements of the two lists. Has anybody an idea how I can achieve this?
Use Collection#retainAll().
listA.retainAll(listB);
// listA now contains only the elements which are also contained in listB.
If you want to avoid that changes are being affected in listA, then you need to create a new one.
List<Integer> common = new ArrayList<Integer>(listA);
common.retainAll(listB);
// common now contains only the elements which are contained in listA and listB.
You can use set intersection operations with your ArrayList objects.
Something like this:
List<Integer> l1 = new ArrayList<Integer>();
l1.add(1);
l1.add(2);
l1.add(3);
List<Integer> l2= new ArrayList<Integer>();
l2.add(4);
l2.add(2);
l2.add(3);
System.out.println("l1 == "+l1);
System.out.println("l2 == "+l2);
List<Integer> l3 = new ArrayList<Integer>(l2);
l3.retainAll(l1);
System.out.println("l3 == "+l3);
Now, l3 should have only common elements between l1 and l2.
CONSOLE OUTPUT
l1 == [1, 2, 3]
l2 == [4, 2, 3]
l3 == [2, 3]
Why reinvent the wheel? Use Commons Collections:
CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)
Using Java 8's Stream.filter() method in combination with List.contains():
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
/* ... */
List<Integer> list1 = asList(1, 2, 3, 4, 5);
List<Integer> list2 = asList(1, 3, 5, 7, 9);
List<Integer> common = list1.stream().filter(list2::contains).collect(toList());
consider two list L1 ans L2
Using Java8 we can easily find it out
L1.stream().filter(L2::contains).collect(Collectors.toList())
You can get the common elements between two lists using the method
"retainAll". This method will remove all unmatched elements from the list to
which it applies.
Ex.: list.retainAll(list1);
In this case from the list, all the elements which are not in list1 will be
removed and only those will be remaining which are common between list and
list1.
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(13);
list.add(12);
list.add(11);
List<Integer> list1 = new ArrayList<>();
list1.add(10);
list1.add(113);
list1.add(112);
list1.add(111);
//before retainAll
System.out.println(list);
System.out.println(list1);
//applying retainAll on list
list.retainAll(list1);
//After retainAll
System.out.println("list::"+list);
System.out.println("list1::"+list1);
Output:
[10, 13, 12, 11]
[10, 113, 112, 111]
list::[10]
list1::[10, 113, 112, 111]
NOTE: After retainAll applied on the list, the list contains common element between
list and list1.
List<String> lista =new ArrayList<String>();
List<String> listb =new ArrayList<String>();
lista.add("Isabella");
lista.add("Angelina");
lista.add("Pille");
lista.add("Hazem");
listb.add("Isabella");
listb.add("Angelina");
listb.add("Bianca");
// Create an aplusb list which will contain both list (list1 and list2) in which common element will occur twice
List<String> listapluslistb =new ArrayList<String>(lista);
listapluslistb.addAll(listb);
// Create an aunionb set which will contain both list (list1 and list2) in which common element will occur once
Set<String> listaunionlistb =new HashSet<String>(lista);
listaunionlistb.addAll(listb);
for(String s:listaunionlistb)
{
listapluslistb.remove(s);
}
System.out.println(listapluslistb);
public <T> List<T> getIntersectOfCollections(Collection<T> first, Collection<T> second) {
return first.stream()
.filter(second::contains)
.collect(Collectors.toList());
}
// Create two collections:
LinkedList<String> listA = new LinkedList<String>();
ArrayList<String> listB = new ArrayList<String>();
// Add some elements to listA:
listA.add("A");
listA.add("B");
listA.add("C");
listA.add("D");
// Add some elements to listB:
listB.add("A");
listB.add("B");
listB.add("C");
// use
List<String> common = new ArrayList<String>(listA);
// use common.retainAll
common.retainAll(listB);
System.out.println("The common collection is : " + common);
In case you want to do it yourself..
List<Integer> commons = new ArrayList<Integer>();
for (Integer igr : group1) {
if (group2.contains(igr)) {
commons.add(igr);
}
}
System.out.println("Common elements are :: -");
for (Integer igr : commons) {
System.out.println(" "+igr);
}
Some of the answers above are similar but not the same so posting it as a new answer.
Solution:
1. Use HashSet to hold elements which need to be removed
2. Add all elements of list1 to HashSet
3. iterate list2 and remove elements from a HashSet which are present in list2 ==> which are present in both list1 and list2
4. Now iterate over HashSet and remove elements from list1(since we have added all elements of list1 to set), finally, list1 has all common elements
Note: We can add all elements of list2 and in a 3rd iteration, we should remove elements from list2.
Time complexity: O(n)
Space Complexity: O(n)
Code:
import com.sun.tools.javac.util.Assert;
import org.apache.commons.collections4.CollectionUtils;
List<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
list1.add(3);
list1.add(4);
list1.add(5);
List<Integer> list2 = new ArrayList<>();
list2.add(1);
list2.add(3);
list2.add(5);
list2.add(7);
Set<Integer> toBeRemoveFromList1 = new HashSet<>(list1);
System.out.println("list1:" + list1);
System.out.println("list2:" + list2);
for (Integer n : list2) {
if (toBeRemoveFromList1.contains(n)) {
toBeRemoveFromList1.remove(n);
}
}
System.out.println("toBeRemoveFromList1:" + toBeRemoveFromList1);
for (Integer n : toBeRemoveFromList1) {
list1.remove(n);
}
System.out.println("list1:" + list1);
System.out.println("collectionUtils:" + CollectionUtils.intersection(list1, list2));
Assert.check(CollectionUtils.intersection(list1, list2).containsAll(list1));
output:
list1:[1, 2, 3, 4, 5]
list2:[1, 3, 5, 7]
toBeRemoveFromList1:[2, 4]
list1:[1, 3, 5]
collectionUtils:[1, 3, 5]
public static <T> List<T> getCommonElements(
java.util.Collection<T> a,
java.util.Collection<T> b
) {
if(a==null && b==null) return new ArrayList<>();
if(a!=null && a.size()==0) return new ArrayList<>(b);
if(b!=null && b.size()==0) return new ArrayList<>(a);
Set<T> set= a instanceof HashSet?(HashSet<T>)a:new HashSet<>(a);
return b.stream().filter(set::contains).collect(Collectors.toList());
}
For better time performance, please use HashSet (O(1) look up) instead of List(O(n) look ups)
Time complexity- O(b)
Space Complexity- O(a)
Below code
Remove common elements in the list
List<String> result = list1.stream().filter(item-> !list2.contains(item)).collect(Collectors.toList());
Retrieve common elements
List<String> result = list1.stream()
.distinct()
.filter(list::contains)
.collect(Collectors.toList());
The question talks about three items and many of the suggestions suggest using retainAll. I think it must be stated that as the size of the lists grown retainAll seems to become more inefficient.
In my tests I found that converting to Sets and looping is around 60 times faster than using retainAll for Lists with 1000s of items
List<Integer> common(List<Integer> biggerList, List<Integer> smallerList) {
Set<Integer> set1 = new HashSet<>(biggerList);
List<Integer> result = new ArrayList<>(smallerList.size());
for (Integer i : smallerList) {
if (set1.contains(i)) {
result.add(i);
}
}
return result;
}
Using Java 8 below solution
list1.stream()
.filter(list2::contains)
.collect(Collectors
.toList()));

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