We cannot perform <Collection>.add or <Collection>.addAll operation on collections we have obtained from Arrays.asList .. only remove operation is permitted.
So What if I come across a scenario where I require to add new Element in List without deleting previous elements in List?. How can I achieve this?
Create a new ArrayList using the constructor:
List<String> list = new ArrayList<String>(Arrays.asList("a", "b"));
One way is to construct a new ArrayList:
List<T> list = new ArrayList<T>(Arrays.asList(...));
Having done that, you can modify list as you please.
Arrays.asList(),generates a list which is actually backed by an array and it is an array which is morphed as a list. You can use it as a list but you can't do certain operations on it such as adding new elements. So the best option is to pass it to a constructor of another list obj like this:
List<T> list = new ArrayList<T>(Arrays.asList(...));
You can get around the intermediate ArrayList with Java8 streams:
Integer[] array = {1, 2, 3};
List<Integer> list = Streams.concat(Arrays.stream(array),
Stream.of(4)).collect(Collectors.toList());
This should be pretty efficient as it can just iterate over the array and also pre-allocate the target list. It may or may not be better for large arrays. As always, if it matters you have to measure.
The Constructor for a Collection, such as the ArrayList, in the following example, will take the array as a list and construct a new instance with the elements of that list.
List<T> list = new ArrayList<T>(Arrays.asList(...));
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList(java.util.Collection)
These days the streams API can easily get you an ArrayList in a concise and functional manner:
Stream.of("str1", "str2").collect(Collectors.toList()));
Of course this also has the flexibility to transform using mappings. For example, while writing unit tests for Spring security code it was convenient to write the following:
Stream.of("ROLE_1", "ROLE_2").map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
The list returned by Collectors.toList is an ArrayList and may be modified as required by your code.
Arrays.asList()
generates an unmodifiable list on object creation. You can use the below code.
List list = Collections.synchronizedList(new ArrayList(...));
This convert allows the list to add and remove objects. I have only tested in java 8.
ArrayList<Object> MyObjectList = new ArrayList<>();
Arrays.asList(params[1]).forEach((item)-> {
MyObjectList.add(item);
});
Related
I would like to sort a List of items in Java and have the sort return a new sorted List without mutating the original List. Is there a commonly used library that does this?
If you are using Java 8 or higher, you can use the Stream API. See Sorting a list with stream.sorted() in Java for details.
For example:
List<String> sortedList = myList.stream().sorted().collect(Collectors.toList());
This copies (by reference) the elements in the original list to the new list. Making changes like the ordering of one list won't affect the other.
List<String> originalList = new ArrayList<String>();
List<String> newList = new ArrayList(originalList);
Please note if you modify the objects that are in the list however, the changes will be reflected in both lists since objects are copied by reference.
In Python there is a data structure called 'List'. By using 'List' data structure in Python we can append, extend, insert, remove, pop, index, count, sort, reverse.
Is there any similar data structure in Java where we can get all that function like Python List?
The closest Java has to a Python List is the ArrayList<> and can be declared as such
//Declaring an ArrayList
ArrayList<String> stringArrayList = new ArrayList<String>();
//add to the end of the list
stringArrayList.add("foo");
//add to the beggining of the list
stringArrayList.add(0, "food");
//remove an element at a spesific index
stringArrayList.remove(4);
//get the size of the list
stringArrayList.size();
//clear the whole list
stringArrayList.clear();
//copy to a new ArrayList
ArrayList<String> myNewArrayList = new ArrayList<>(oldArrayList);
//to reverse
Collections.reverse(stringArrayList);
//something that could work as "pop" could be
stringArrayList.remove(stringArrayList.size() - 1);
Java offers a great selection of Collections, you can have a look at a tutorial that Oracle has on their site here https://docs.oracle.com/javase/tutorial/collections/
IMPORTANT: Unlike in Python, in Java you must declare the data type that your list will be using when you instatiate it.
Several collections exist, but your probably looking for ArrayList
In Python you can simply declare a list like so:
myList = []
and begin using it.
In Java, it better to declare from the interface first so:
List<String> myList = new ArrayList<String>();
Python Java
append add
Remove remove
len(listname) list.size
Sorting a List can require a little more work, for example, depending on the objects you may need to implement Compactor or Comparable.
ArrayList will grow as you add items, no need to extend it on your own.
As for reverse() and pop(), I'll refer you can refer to:
How to reverse a list in Java?
How to pop items from a collection in Java?
Java has an interface called list, which has implementations such as ArrayList, AbstractList, AttributeList, etc.
https://docs.oracle.com/javase/8/docs/api/java/util/List.html
However, each one has different functionalities, and I don't know if they have everything you've specified such as .reverse().
Take a look at Collections in java. There are many lists (ArrayList, LinkedList etc). Choose the best datastructure needed for the requirement and complexity (both space and time).
I want to create a list of list
List<integer> nodes[10]=new ArrayList();
i want this, coz i will be iterating through it and reading data..and it will be dynamically created in runtime depending upon the size of inputs
Creating an array of List seems a little weird to me, not that you can't do it, it just seems counter intuitive to me...
Instead, I'd create a List of Lists, something like...
List<List<Integer>> nodes = new ArrayList<List<Integer>>(10);
You would then just need to populate them with actually values, this will depend on what you are doing, but something like...
nodes.add(new ArrayList<Integer>(10));
When you need to access a particular list/node, you would just access it like any normal List
List<Integer> listOfIntegers = nodes.get(0);
Take a look at the Collections tutorial and List JavaDocs and ArrayList JavaDocs for more details.
An array of ArrayLists
List<Integer>[] nodes = new ArrayList[count];
An ArrayList of ArrayLists
List<List<Integer>> nodes = new ArrayList<List<Integer>>(count);
I'm trying to add data into array list. in this result
[{Store={id_store=2, namestore=Kupat Tahu Singaparna , product=[{id_product=1, price=100000, quantity=1}]}}]
you could use this code:
static ArrayList Storecart = new ArrayList();
LinkedHashMap store = new LinkedHashMap();
LinkedHashMap storeitem = new LinkedHashMap();
LinkedHashMap listproduct = new LinkedHashMap();
ArrayList prdct = new ArrayList();
storeitem.put("id_store",id_store);
storeitem.put("namestore",namestr );
listproduct.put("id_product", id_prodt);
listproduct.put("price",priced);
listproduct.put("quantity", quantity);
prdct.add(listproduct);
storeitem.put("product", prdct);
store.put("Store", storeitem);
Storecart.add(store);
I need to get the index of an object in the array list. The problem is, I can't looping array list for "get object Store, and object product" and find every index.. what will be the best & efficient solution ?
Well, you could use List.indexOf(), as others have suggested:
Java List API: indexOf()
If you plan on doing this a lot, then presumably you have a handle on your Object reference. So, you could just extend/wrap the Object you want the index of to keep track of its own index. Specifically, you could assign the Object its index based on the order you first encounter it or something. The order of the Object in the Collection would then be irrelevant.
I suppose you could also use a Map as yet another possibility. Then only work with the Map instead of an ArrayList.
Bottom-line: if you're doing a lot of "indexOf()" requests, then the ArrayList may not be the best container for your data.
I have an ArrayList.
How can I instantiate a new List with the same data but sorted?
I thought about the following:
Use the ArrayList copy constructor and then use Collections.sort
Use a TreeSet
For option (1) there is the extra overhead of copying the elements and then sorting.
For option (2) duplicates will be removed.
What is the best way for this?
If you can use third-party libraries, then with Guava this is just
List<Foo> sortedCopy = Ordering.from(comparator).sortedCopy(list);
(Disclosure: I contribute to Guava.)
The "best way" depends on your requirements: do you want the duplicates removed? Use a TreeSet; do you want to keep the duplicates? Copy, then sort. Trying to get the fastest one out of the two is premature optimization.
In Java 8 you can use streaming:
ArrayList<Integer> myArrayList = new ArrayList();
myArrayList.add(4);
myArrayList.add(6);
List<Integer> myNewSortedList = myArrayList.stream().sorted().collect(Collectors.asList());
However, the list above must not be mutated. If you want that, you can instead collect as an ArrayList:
myArrayList<Integer> myNewSortedList = myArrayList.stream().sorted().collect(Collectors.toCollection(ArrayList::new));
Don't use a Treeset to get a sorted copy of a List. It'll remove duplicates. (Unless this is what's desired, but then it's a different problem from creating a new sorted copy of a List).
Use option 1 - Create a new List and call Collections.sort() on it, and possibly use your own Comparator if desired.