Reputation: 11187
I have a LinkedHashMap that stores an order number as the key and a string value as value:
{12,"apple"}
{1,"grape"}
{23,"pineapple"}
{2,"pear"}
{16,"cherry"}
I need to sort them by key before I do anything else with them. I'm looking into writing a comparator but a bit lost on how to do that with what I'm trying to accomplish.
Upvotes: 0
Views: 961
Reputation: 227
If you need to store Map
in some order, you must use TreeMap
instead of LinkedHashMap
. LinkedHashMap
just store element in order to add elements.
Use TreeMap
in this way
TreeMap<Integer, String> map = new TreeMap<Integer, String>(
new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
if (o1 > o2) return 1;
if (o1 < o2) return -1;
else return 0;
}
}
);
Upvotes: 0
Reputation: 340
Look into using a TreeMap instead, which will sort the elements you add to it in ascending order based on the Integer key automatically.
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
treeMap.add(1, "foo");
treeMap.add(3, "baz");
treeMap.add(2, "bar");
Iterating over this TreeMap in order of ascending integer keys will print "foo bar baz".
Upvotes: 1
Reputation: 13705
By nature Maps are "Unordered/Unsorted" collections, if you need something like that there's other methods you can use, like SparseArray(which is better suited for int/value elements), you could create a list of your int keys, sort it, and then iterating through them getting the values as follows:
//This would be your SparseArray
{12,"apple"}
{1,"grape"}
{23,"pineapple"}
{2,"pear"}
{16,"cherry"}
int[] sortedInt = {1,2, 12, 16, 23};//Previously sorted values using any Java sorting functionality
for(int i = 0 ; i < sortedInt.length; i++){
String value = yourSparseArrat.get(sortedInt[i]);
}
And there you go, by sorting your keys and then getting the values in that order you get what you need.
Regards!
Upvotes: 0
Reputation: 1566
Just like NKN said before, HashMap
's are not meant to be ordered. the Benefit of the LinkedHashMap
is that it maintains the insertion error, however it doesn't provide you with a sorting mechanism.
in order to accomplish that you want to create a POJO class to hold you data
public class fruit {
int count;
String name;
// getters and setter
}
than make that object implement the Comparable
interface, and override the compareTo()
method. Once that is done you can call
Collections.sort(linkedHashMap)
Upvotes: 0
Reputation: 13761
Usually anything that has the Hash
name in its type is not intended for ordering, at least not the way most people order. Hash structures are precisely so efficient because they have their own access/retrieve functions based in a hash that make allocate items not in the way we know as "ordered", so this way they are very efficient for access and writing but they don't allow that kind of ordering.
Upvotes: 2