How can you sort values in HashMap [duplicate] - java

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.

Related

How to sort a HashMap, values are integers. I want to sort from highest to lowest [duplicate]

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));

Sort list of countries [duplicate]

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<>();

Hash map with multiple keys? [duplicate]

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);

Strings as key in Hashmap [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I'm newbie with Java
Is it possible to convert a String, or a String[] as the keys of an Hashmap?
I mean:
String keysToConvert = "key1,key2,key3";
into
HashMap<String, Double> hashmap = new HashMap<String, Double>();
[apply in some way the keys of the string]
hashmap.get("key2");
I know that hashmap.get("key2");has no value in this moment. I just would know if there is a way to load the keys in an HashMap.
hashmap.put("key2", 1.0d);
System.out.println(hashmap.get("key2")); // prints 1.0
This is the basic usage of a Map
If you have String[], you can add them using a for-each loop:
String[] keys = {"key1", "key2", "key3"};
HashMap<String, Double> hashmap = new HashMap<String, Double>();
for (String key : keys) {
hashmap.put(key, null);
}

how to sort hashmap by values? [duplicate]

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());

Categories

Resources