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.
Related
I have an arraylist of Objects where i am pulling them in Java from a Sparql Query placing them into an arraylist with while(result.hasNext()).
The problem is that i have to take the results based on their URI from the query. So Object1 comes first, then comes 10,11 etc and after all comes Object2.
I want the Objects to be placed in order inside the arraylist (1,2,...,10,11..). I have tried to sort the arraylist based on some property and i want to avoid counting the Objects and then make the arraylist the same count of Objects and use add(index, Object).
Is there a way to do it without knowing the size of the arraylist?
Thank You.
implement equals() method in your class which present in arrylist and then use Collections.sort() to sort your array list.
Try the Collections.sort(List, Comperator) method.
Just add all results from your query to the List and sort it with a given Comperator. In this comperator you have to implement the compare() method to fit your needs.
I get what you need. You don't need to use a Comparator:
String s = uri.toString();
//trim your string to return only the Object index.
int i = Integer.parseInt(s);
list.add(i, Object);
or you could use a Map and retrieve the Objects by URI
Map<URI, Object> = new HashMap<>();
map.put(URI, Object);
Basically what I'm trying to do is store two values into a hashmap, i've tried a dictionary and failed with that as-well, anyhow, here we go.
private HashMap<Integer, Integer> dropTable = new HashMap<Integer, Integer>();
Then, in my code I have this
for(int npc = 0; npc < 10; npc++){
dropTable.put(npc, Constants.itemDrops[npc][1]);
}
Basically, what I'm trying to do is save the values in this manner (With the ItemID being what is returned in the itemDrops array
<ArrayIndex, ItemID>
How,ever when I try to return this information, i can't figure it out.
Here is how I attempted returning this value
for(int i = 0; i < dropTable.size(); i++) {
System.out.println("NPC: " + dropTable.get((Integer)i));
}
However, that returns null, and looking at it, it wont give me what I need.
How would I go about retrieving the Key/Value separately from the HashMap based on the Index of the HashMap? (If Hashmaps even have Index's, that's what I'm under the impression of)
===============
My idea of a hashmap.
<Integer>, <Integer> Index: 0
<Integer>, <Integer> Index: 1
etc...
HashMaps are unsorted, do not have indexes and the order features are returned during iteration is not guaranteed to be the order of insertion.
There are other Map objects available which provide some of these features. TreeMap is sorted for example.
All Maps provide a method keySet() which provides the set of Keys in an iterator and a similar values() Collection iterating over these objects is likely to provide the sort of behavour you wish.
First thing to aks, is a hashmap realy the data structure you need?
If not not then just use a simple List and use its get(index) method!
If Yes then you could use a Map implmentation - such as LinkedHashMap - that preserves the insert/put order. Then you can call values() of that map and iterate over it using enhanced for-loop, or probably also create a List and passing it the collection reurned if you need index access.
If you are looking to get a your objects according to an index - what you are really looking for is an ArrayList - which allows access by index, and is basically a dynamic array.
If you want to objects "attached" to the same index, you can use 2 ArrayLists (one for each type of object) - or use a Pair (from apache commons) as an element in the arraylist.
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);
});
What I'm doing is storing classes into an ArrayList and retrieve them by its index number. But are there any list classes in Java where I can retrieve a list element by, lets say, its name? Like this:
ArrayList<string> myArr = new ArrayList<string>();
myArr.add( "ID_name", "String to store" );
ands then retrieve it by:
myArr.get( "ID_name" );
Also, are there any other alternatives to ArrayList? I need a list class to be optimized for:
Random access
Only need to push items into the list
Never need to delete anything from the list
If all you want to store is key-value pairs, and don't care about iteration order, I think you might like the HashMap class:
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
String bar = map.get("foo"); // bar is "bar"
You can use LinkedHashMap, so it will preserve the order, but you can extract elements by key as in regular map. Though you won't be able to extract entries by index.
An ArrayList is just that: an array. If you want to access values by something else than their indices, look for the various implementations of the Map interface (such as HashMap).
Use a Map<String, String>. In such structure, an element is added with a key. So you can get the element through the key:
Map<String, String> map = new HashMap<String, String>();
map.put("id", "string");
String s = map.get("id"); // s will be equals to "string".
As the other people have mentioned, a HashMap is probably what you want if you don't care about iteration order.
If you do, you can use a LinkedHashMap, which is really a HashMap bolted onto an LinkedList, giving you the best of both worlds: fast random access and preservation of iteration order.
Use a hashmap. You can add elements to a hashmap in much the same way as an arraylist. Also, you can create a set of keys ( 1 elements in the set per (key, value) pair)). You can then iterate over the set of keys.
I tried to create a list of maps. In the following code, I'm expecting to get
[{start=1,text=ye}, {start=2,text=no}]
however, I only got
[{start=2,text=no}, {start=2,text=no}]
How to avoid overriding the first map? Here is my code:
HashMap mMap = new HashMap();
ArrayList list = new ArrayList();
list.add(new HashMap());
mMap.put("start",1);
mMap.put("text","yes");
list.add(mMap);
mMap.put("start",2);
mMap.put("text","no");
list.add(mMap);
System.out.println("Final result: " + list );
thanks!
==========================
As a learner of Java who came from a procedure language background (SAS), I spent quite a few hours learning and experimenting ArrayList, LinkedList, Map, LinkedMap, etc--- I coldn't get it to work. And I don't understand why with my limited knowledge. Now, these following answers are all excellent! They explained very important data structure in Java, at least for me.
THANK YOU ALL!!!!
You need to create a new HashMap for every entry, instead of reusing the existing one. This would work:
HashMap mMap = new HashMap();
mMap.put("start",1);
mMap.put("text","yes");
list.add(mMap);
mMap = new HashMap(); // create a new one!
mMap.put("start",2);
mMap.put("text","no");
list.add(mMap);
also, you can remove the list.add(new HashMap()); as that adds an empty map to your list that is never populated.
Something which is maybe also worth mention it, is that you should define the type of the elements you use in the List, for the HashMap its not possible because you are mixing Integers and Strings.
And another thing is that you should use the List interface as type, so you are able to change the implementation (ArrayList or whatever) in the future.
Here the corrected code:
Map mMap = new HashMap();
List<Map> list = new ArrayList();
Yes, hash map from this piece of code
list.add(new HashMap());
is never referenced. So eventually you get a list of 3 items, 2 of which are identical however.
You are never saving a reference to this Map:
list.add(new HashMap());
have three adds to the list. the first add is to a new map instance; you never set any values. The second add you pass in a reference to nMap, which has 1, yes. The third add you pass the same reference. So the Map now has 3 references, the first to a map you never added any values to, the next 2 to the same map. which is why you get the same output.
When you put the same key name in the map then values will be overridden to same key.
suppose we have
mMap.put("start",1);
mMap.put("start",2);
mMap.put("start",3);
mMap.put("start",4);
it will not make map of length 4, as the key("start") is same so it will override the values on the same key. so you will get the get only one value (4) against "start" key.
To avoid this you will have to change the name of keys in a hashmap but in your scenaro, you need an other instance of hashmap to save the key and values as you are maintaining the arralist.