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.
Related
I would like if someone could explain me what is the meaning of this in java
List<HashMap<String, String>> nearbyPlacesList
That means that you have a List containing instances of HashMaps that takes String data as both keys and values.
Oh, and the variable is called nearbyPlacesList.
It's a List which contains HashMap elements with a key of String type and a value of String type.
It is a List consisting of possibly multiple HashMap's where the key-value are Strings.
e.g.
nearbyPlacesList.get(0); // returns first HashMap in the List
nearbyPlacesList.get(0).get("park"); // returns value of the first Map which has the key park
and so on.
A HashMap contains key-value pairs of different kinds (in your case String).
Let's take an example right here. A store. In a store there can be different clothes.
HashMap<String, String> tShirts;
HashMap<String, String> jeans;
where the key-value pair could be for example "Price" and "100€", and they can all be stored in the following list containing different clothes:
List<HashMap<String, String>> clothes;
clothes.add(tShirts);
clothes.add(jeans);
The first piece of information that we see is a list, so we know it's a list. Then we see it is a hashmap (take a look here at the java docs if you are not familiar https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html)
So it's a list of hashmaps, with two strings as the key value pair.
HashMap<String,String>
It uses to store your data as a key and value pair.
When There is more than one HashMap you want to store. you can store all hashmaps into a single list like this.
List<HashMap<String,String>>
How can I get the key position in the map? How can I see on which position is "Audi" and "BMW"?
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Audi", 3);
map.put("BMW", 5);
As other answers state you need to use a structure like java.util.LinkedHashMap. LinkedHashMap maintains its keys internally using a LinkedEntrySet, this does not formally provide order, but iterates in the insertion order used.
If you pass the Map.keySet() into a List implementation you can make use of the List.indexOf(Object) method without having to write any of the extra code in the other answer.
Map<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("Audi", 3);
map.put("BMW", 5);
map.put("Vauxhall", 7);
List<String> indexes = new ArrayList<String>(map.keySet()); // <== Set to List
// BOOM !
System.out.println(indexes.indexOf("Audi")); // ==> 0
System.out.println(indexes.indexOf("BMW")); // ==> 1
System.out.println(indexes.indexOf("Vauxhall")); // ==> 2
You can't. The keys on a Map and a HashMap are not ordered. You'll need to use a structure that preserves order, such as a LinkedHashMap.
Note that LinkedHashMap does not provide a method that gets keys by position, so this is only appropriate if you are going to be using an iterator.
The alternative is to create a second Map that maps from your key to the Integer position, and add to it as you go along:
Map<String, Integer> indexMap = new HashMap<String, Integer>();
indexMap.put("Audi", 0);
indexMap.put("BMW", 1);
For a more elegant solution, you might need to give more information about what you're doing.
You can't. From the HashMap JavaDocs:
Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
So, the order may vary between iterations. If you need to preserve the order you can take a look at LinkedHashMap
From the LinkedHashMap JavaDocs:
Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
So, to find the key position you basically need to iterate the keys and count the position of the key you are searching for.
On a side note, IMO this may not be the best use of the Map datatype. I believe that if you really need the position you should use some type of List (e.g. ArrayList) that actually preserves the order and you can use the get method to retrieve elements for a certain index.
public static HashMap<ArrayList<Integer>, String> map = new HashMap<ArrayList<Integer>, String>();
public static ArrayList<ArrayList<Integer>> keys = new ArrayList<>(map.keySet());
Then in main
map.put(key, "c");
(assume key is a valid ArrayList). But keys still has size 0 after that.
How can I make the relationship of keys stronger so that it will be actually tied to the HashMap and contain all its keys.
The copy constructor of ArrayList copies all the keys in the map to the ArrayList but if you change the map after that point it will not be reflected.
I can think of 3 options:
write your own map implementation that embeds an ArrayList and keeps it up to date
update the ArrayList manually everytime you update the map
don't use an ArrayList at all (keySet() is there when you need to access the keys so I'm not sure why you would need one)
You can't.
Map.keySet() returns the Map's current key set, which you then load into your list. Changes to the map after that have no effect on the contents of the list.
Most people would just re-get the key set if needed. Why don't you just do that?
I am inserting four values with different keys in a HashMap.
Code Snippet :
HashMap<Integer, String> choice = new HashMap<Integer, String>();
choice.put(1, "1917");
choice.put(2, "1791");
choice.put(3, "1902");
choice.put(4, "1997");
But when I am printing that map values,it returns a result something like :
{4=1997, 1=1917, 2=1791, 3=1902}
How can I get the map values in a sequential order the way I have put/inserted?
You can use a LinkedHashMap instead, which will keep the insertion order:
This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
You can modify your code like this:
Map<Integer, String> choice = new LinkedHashMap<Integer, String>();
//rest of the code is the same
LinkedHashMap, which is a Hash table and linked list implementation of the Map interface can be used.
It maintains the same order in which the values are inserted using doubly linked list.
Reference : http://docs.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashMap.html
[Edit]What the OP asks is not entirely clear to me. The OP could be asking, "How do I retrieve items from a map in insertion order?" If that is what the OP meant, then the following information is not a solution.
If the OP is asking, "How do I retrieve items from a Hash sorted by the key?" then the following is on-point. Getting the sorted keys of a hash/associative array is a common operation.
The answer can be found in how to sort Map values by key in Java:
List sortedKeys=new ArrayList(yourMap.keySet());
Collections.sort(sortedKeys);
If you care about the order in which the keys are stored and retrieved, consider using a TreeMap instead. Unless you have a very large number of elements (millions+), the performance difference is not likely to be noticeable.
I have a Map Map<Integer, List> with key, values. I need to convert this into List and pass it to the calling function. Once I have the list i need to convert this back to Map<Integer, List>
The reason I am converting the map to list is because i need to create webservice for this method. As I cannot expose the Map to webservice I need to convert this to list.
How to achieve this..?
A map has two functions called keySet() and values(). They return the keys and values of the map respectively. The keyes are returned as a Set and the values as a Collection.
You can create a list from either of these.
Here is an example:
Map<Integer, List> map = // map creation;
List<Integer> keyList = new ArrayList<Integer>(map.keySet());
List<List> valueList = new ArrayList<List>(map.values());
From what i read you are trying to pass map via list (as your service limitation).
In case you don't find any better solution, you can always use two lists. One for keys and one for values.
(but you are risking breaking map consistency with this approach).
You can create a class with two attributes (Integer, List) and create a List with one object by key.
Also, you can use:
new ArrayList(Map.entrySet());
and convert the resulting set to a list.
To get the values (Strings):
List<List<String>> listVals = new ArrayList<List<String>>(map.values());
To get the keys:
List<Integer> listKeys = new ArrayList<Integer>(map.keySet());
A map contains key value pair but list does not contains key value pair. So u can create a bean class to set key and values and then create list which contains objects of the bean class.