I have a HashMap which has keys as Date in Strings and value as an ArrayList of custom objects. I want to sort this hashmap on the basis of key. How can I do that?
HashMap<String,List<ClassName>> hashmap = new HashMap<String,List<ClassName>>();
When Hashmap is like this:
{"2015/07/15 : List("Object1","object2","object3")
"2015/07/14 :List("Object4" , "Object5")}
Please suggest.
You can use TreeMap instead of a HashMap . The TreeMap implements the Sorted Map interface.
As well as using a sorted map (as others have suggested) you can easily sort the keys when you use them rather than when you insert them.
For example, in Java 8:
treeMap.keySet().stream().sorted().forEach(System.out:println);
A nice thing about this is that it's easy to sort using different comparators without changing the collection.
For example, if you wanted to to sort by the number of items in the list value:
treeMap.keySet().stream().sorted(Comparator.comparingInt(k -> treeMap.get().size()))
This method is good for situations in which you insert and change values in the map often and then occasionally need the keys sorted for a particular operation. You get the performance of a HashMap but the flexibility to sort however you want on use.
You can use TreeMap, if you need the sorted map.
If you don't want to use TreeMap, then get the key and sort it as below.
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
map.put("2015/07/15", list);
map.put("2015/07/17", list1);
map.put("2015/07/16", list1);
ArrayList<String> keyset = new ArrayList<String>(map.keySet());
Collections.sort(keyset);
First thing is you can use TreeMap when you need a sorted map. However you are storing date value as Strings. Then it become harder to compare each. So i recommend to use java.util.Date instead of String. You can use a date formatter when you adding to the map. Use following code.
TreeMap<Date, List> treeMap = new TreeMap<>();
You can specify the Comparator in the constructor of the TreeMap. So it's easy to sort up things according to your custom order.
Related
I am trying to get values from an ArrayList that is sorted and want to store it in a HashMap, where the values of the ArrayList become keys of the HashMap. Will the order of the values in the HashMap still be the same as that of ArrayList?
No. Use a TreeMap instead. This will preserve the order of insertion.
HashMap makes no guarantees as to the order the mappings are stored or iterated, so simply running through the ArrayList and putting them into the HashMap as keys will very likely result in unordered iterations.
As others have pointed out, LinkedHashMap does preserve insertion order for iterations. An additional run of insertions will result in unordered iterations again, though. Both HashMap and LinkedHashMap support constant time lookup - LinkedHashMap pays for its extra feature in space (by maintaining pointers between the keys).
As others have also pointed out, TreeMap preserves order after updates, so this might be a better option for you, or not. Of course, if the ArrayList is sorted with a specific Comparator, you must feed that same Comparator to the TreeMap on construction for the sorting to be the same. Note that TreeMap does not have constant time lookup, due to being implemented as a Red-Black search tree.
As your ArrayList has been ordered, no need to use a TreeMap because this will compare to order again and it's not necessary. You should use a LinkedHashMap that will keep the exact order of your ArrayList when you put your value in.
Check This: Insert Values of ArrayList into HashMap
HashMap<String, Item> itemMap = new HashMap<String, Item>();
for (Item item : itemList)
{
itemMap.put(item.getitemCode(), item);
}
I was wondering if it is possible to compare items in multiple hashMaps to each other:
HashMap<String,String> valueMap = new HashMap<String, String>();
HashMap<String,Integer> formulaMap = new HashMap<String, Integer>();
What I would basically like to do is something like:
if(the second string in valueMap is the same as the first string in formulaMap){
}
Is there a short way to achieve this or do I have to compare the strings before they are included into the hashMaps. My Integer at this stage of the program is required to take a null value. I can achieve my goals with a multi-dimensional array, but a solution like this would be more elegant and less time consuming.
By using a LinkedHashMap you can have a map that respects the insertion order of different values. Everything you have to do is iterate over the entrySet of the map until you reach the position you're looking for.
Plus: If you also need ordering, you can have a look at the TreeMap which inserts elements in order based on a criteria defined by you (You can pass a Comparator as a parameter for the map).
This order will apply to the keys of the map tough, so if you need value ordering you're going to have to come up with a little more complex solution (as in sorting the entry set directly and adding the values to another map, for example).
I have situation where there is a HashMap as
Map<Integer,ArrayList> key = new HashMap<Integer,ArrayList>();
The array list has [rankOfCard,suitOfCard]
I want to sort this Map in such a way that If the value is
(1,[3,1])
(2,[2,4])
(3,[1,3])
(4,[1,2])
(5,[2,3])
Output should be :
(4,[1,2])
(3,[1,3])
(5,[2,3])
(2,[2,4])
(1,[3,1])
How can I achieve this ?
Iterate through entry set and Collection.sort(entry.value())
A Map is not sorted, so it's not the right data structure for your task.
A SortedMap sorts on keys, so it's no good as well, since you want your map sorted by value.
Your question does not clarify what the key of the Map is, but maybe you could use a custom class in a regular List, and have the class implement the Comparable interface, or implement an external Comparator, to sort the List.
I need to have a HashMap< Integer, String> which can serve fast operations for retrieving a list of all entries whose keys are in a certain integer range besides, getting values from map based on keys.
What Map implementation is suitable for these needs ?
You are probably looking for a NavigableMap. However, you can't use HashMap to create one, because the map would have to be a SortedMap. Consider using TreeMap instead.
Use a TreeMap, which implements NavigableMap supplying a subMap method returning a view of the map with only keys in your range. To get the values, of course you call values() on the result.
If you have an existing Map whose keys implement Comparable, you can construct a TreeMap from it by calling new TreeMap(existingMap), but it will likely be more efficient to create it as a TreeMap from the start.
TreeMap will provide a sorted list of keys. You would then need to trim the list to get your range of values.
I'm looking for a way to maintain the sorting on my key-value pairs. They are sorted by variables outside of the actual key-value pairs (for better UI). I am currently using a Hashtable, but that does not maintain the sorting =(
Hashtable<Integer, String> subscriptions = getUsersSubscriptions(user);
Is there some simple way that Java lets one store pairs? The best idea I can think of is using 2 associated ArrayLists (one of type Integer, another of type String). Can someone think of something better?
If your key-value pairs are already sorted, LinkedHashMap will maintain order of insertion.
In other words, the keys returned by map.keySet() will be in the exact order you put them into the map.
SortedMap<Integer, String> myMap = new TreeMap<Integer,String>();
If you have a custom sorting, pass a Comparator instance to the constructor of the TreeMap. But be careful doing so, as using a Comparator that does not go well with natural Integer order would make things impossible to understand and debug.
LinkedHashMap can be used here.
Is there some simple way that Java lets one store pairs?
Create a custom class that stores the two properties.
They are sorted by variables outside of the actual key-value pairs
Add a third property for the sort data.
Then your class can implement Comparable to sort the data as required based on this property.
Or you can use a custom Comparator to sort on the sort data field.
Now the class instances can be stored in an ArrayList.