This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to sort a Map<Key, Value> on the values in Java?
I need to sort my hashmap according to the values stored in it. The hashmap contains the contacts name stored in phone.also I need that the keys get automatically sorted as soon as I sort the values.or you can say the keys and values are bounded together thus any changes in values should get reflected in keys.
HashMap<Integer,String> map = new HashMap<Integer,String>();
map.put(1,froyo);
map.put(2,abby);
map.put(3,denver);
map.put(4,frost);
map.put(5,daisy);
required output:
2,abby;
5,daisy;
3,denver;
4,frost;
1,froyo;
private static class MyMapComparator implements Comparator<Map.Entry<Integer, String>>
{
#Override
public int compare(Map.Entry<Integer, String> a, Map.Entry<Integer, String> b) {
return a.getValue().compareTo(b.getValue());
}
}
...
List<Map.Entry<Integer, String>> entries = new ArrayList<Map.Entry<Integer, String>>(map.entries());
Collections.sort(entries, new MyMapComparator());
Related
This question already has answers here:
Sorting Hash Map by values [duplicate]
(3 answers)
Sort a Map<Key, Value> by values
(64 answers)
Closed 1 year ago.
So, I need to sort a "scores" hashmap. the hashmap layout is HashMap<Player, Integer(which is the score i need to sort>
if you're asking why? its because i need to make a leaderboard.
here is my code:
public static Player[] sortPlayersByElo() {
Map<String, Object> map = RankingConfig.get().getConfigurationSection("data").getValues(false);
Map<Player, Integer> eloMap = new HashMap<>(); // Here is the map i need to sort.
for (String s : map.keySet()) {
Player player = Bukkit.getPlayer(s);
eloMap.put(player, RankingConfig.get().getInt("data."+s+".elo"));
}
Player[] players = new Player[eloMap.size()];
return players;
}
You can use Comparator.comparingInt to sort in the correct order. Streams can be used to sort and collect the new Map to a LinkedHashMap to retain the new order.
Map<Player, Integer> result = eloMap.entrySet().stream()
.sorted(Comparator.comparingInt(Map.Entry::getValue))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(a,b)->b, LinkedHashMap::new));
This question already has answers here:
How to preserve insertion order in HashMap? [duplicate]
(2 answers)
Closed 4 years ago.
I want to generate a list of all countries in a sorted list. I tried this:
public Map<String, String> getCountryNameCodeList() {
String[] countryCodes = Locale.getISOCountries();
Arrays.sort(countryCodes);
Map<String, String> list = new HashMap<>();
for (String countryCode : countryCodes) {
Locale obj = new Locale("", countryCode);
list.put(obj.getDisplayCountry(), obj.getCountry());
}
return list;
}
But for some reason the list is unsorted. What is the proper way to fort it?
HashMap is unsorted, use LinkedHashMap:
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).
Just change
Map<String, String> list = new HashMap<>();
to:
Map<String, String> list = new LinkedHashMap<>();
This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 5 years ago.
I want to sort this HashMap:
HashMap<Integer,Integer> hp=new HashMap<Integer,Integer>();
TreeMap<Integer,Integer> stm = new TreeMap<Integer,Integer>();
stm.putAll(hp);
In value reverse sorting.
If the values are the same, I will use key as the next condition.
Value is reverse but key is not.
We can implement the sort of HashMap by referring to TreeMap's value sort.
I tried to write a sample to share with you.
public class HashMapTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("c", "ccccc");
map.put("a", "aaaaa");
map.put("b", "bbbbb");
map.put("d", "ddddd");
List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
Collections.sort(list,new Comparator<Map.Entry<String,String>>() {
//Ascending order
public int compare(Entry<String, String> o1,
Entry<String, String> o2) {
return o1.getValue().compareTo(o2.getValue());
}
});
for(Map.Entry<String,String> mapping:list){
System.out.println(mapping.getKey()+":"+mapping.getValue());
}
}
the resule is
a:aaaaa
b:bbbbb
c:ccccc
d:ddddd
Why don't you get the entrySet from the map and try sorting it by using creating a comparator according to your need. When it's sorted just create a new instance of map and iterate the sorted set into the map. Its a little costly but does what you need.
If you find any problems implementing this. Tell me I will give you the code. :)
This question already has answers here:
How to create a HashMap with two keys (Key-Pair, Value)?
(14 answers)
Closed 6 years ago.
Can I have a hash map in Java that looks like this?
HashMap<String, String, Integer> hmap = new HashMap<String, String, Integer>()
My question is similar to this one hereQuestion
I'm a newbie to Java. So what I want to know is, what would be the best data structure to use if I need something like above, if that is not valid?
Create a simple class holding two String objects:
public class MyKey {
private String a;
private String b;
// ... accessors, mutators etc.
}
And then use it's objects as keys in your map:
HashMap<MyKey, Integer> hmap = new HashMap<>()
Later, to add a new entry:
hmap.put(new MyKey("a", "b"), 2);
This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 9 years ago.
For example you have a HashMap<String, String>
how can you sort values in the hashmap and print them to console
what would be the best ways to do it?
This should do it:
Map<String, String> asso = new HashMap<String, String>
// add some tuples to asso
List<String> values = new ArrayList(asso.values());
Collections.sort(values); // assumes an appropriate comparator implementation for the value type
There isn't a way to retrieve a HashMap tuple by value sorted order afaik.