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<>();
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 6 years ago.
I'm making use of the ExpandableListView and I have a few lists set in an array lists.
I set them to be in a certain order which is:
company, day of the week, posh vehicles, topgear vehicles
but what ever I do the order reverts to
posh vehicles, company, days of the week, topgear vehicles
Can anybody help me figure out the problem here is the code I'm using for the stringArray?
public static HashMap<String, List<String>> getData() {
HashMap<String, List<String>> expandableListDetail = new HashMap<String, List<String>>();
List<String> listDataHeader = new ArrayList<String>();
// Adding child data
listDataHeader.add("Company");
listDataHeader.add("Please pick a day");
listDataHeader.add("Posh Vehicles");
listDataHeader.add("TopGear Vehicles");
List<String> CompanyName = new ArrayList<>();
CompanyName.add("Posh limos");
CompanyName.add("TopGear limos");
List<String> daysOftheWeek = new ArrayList<>();
daysOftheWeek.add("Monday");
daysOftheWeek.add("Tuesday");
daysOftheWeek.add("Wednesday");
daysOftheWeek.add("Thursday");
daysOftheWeek.add("Thursday");
daysOftheWeek.add("Friday");
daysOftheWeek.add("Saturday");
daysOftheWeek.add("Sunday");
List<String> poshvehicles = new ArrayList<>();
poshvehicles.add("Posh H2 limo");
poshvehicles.add("Iveco party bus");
poshvehicles.add("Merc party bus ");
poshvehicles.add("Party coach");
List<String> topGearVehicles = new ArrayList<>();
topGearVehicles.add("TopGear H2 limo");
topGearVehicles.add("TopGear party bus");
expandableListDetail.put(listDataHeader.get(0),CompanyName);
expandableListDetail.put(listDataHeader.get(1),daysOftheWeek);
expandableListDetail.put(listDataHeader.get(2),poshvehicles);
expandableListDetail.put(listDataHeader.get(3),topGearVehicles);
return expandableListDetail;
The HashMap doesn't keep the insertion order.
You can use a LinkedHashMap instead (which extends HashMap):
Map<String, List<String>> expandableListDetail = new LinkedHashMap<>();
I also used the interface name on the left side Map and the diamond operator (<>) that works if you have at least Java 7.
This question already has answers here:
Java Class that implements Map and keeps insertion order?
(8 answers)
Closed 9 years ago.
So i've created an hashmap, but i need to get the first key that i entered.
This is the code i'm using:
First:
public static Map<String, Inventory> banks = new HashMap<String, Inventory>();
Second:
for(int i = 0; i < banks.size(); i++) {
InventoryManager.saveToYaml(banks.get(i), size, //GET HERE);
}
Where it says //GET HERE i want to get the String from the hasmap.
Thanks for help.
HashMap does not manatain the order of insertion of keys.
LinkedHashMap should be used as it provides predictable iteration order which is normally the order in which keys were inserted into the map (insertion-order).
You can use the MapEntry method to iterate over your the LinkedHashMap. So here is what you need to do in your code. First change your banks map from HashMap to the LinkedHashMap:
public static Map<String, Inventory> banks = new LinkedHashMap<String, Inventory>();
And then simply iterate it like this:
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
If you just need the first element of the LinkedHashMap then you can do this:
banks.entrySet().iterator().next();
Answering the question in the title: to get the first key that was inserted, do this:
public static Map<String, Inventory> banks
= new LinkedHashMap<String, Inventory>();
String firstKey = banks.keySet().iterator().next();
Notice that you must use a LinkedHashMap to preserve the same insertion order when iterating over a map. To iterate over each of the keys in order, starting with the first, do this (and I believe this is what you intended):
for (Map.Entry<String, Inventory> entry : banks.entrySet()) {
InventoryManager.saveToYaml(entry.getValue(), size, entry.getKey());
}
This question already has answers here:
Does Java have a HashMap with reverse lookup?
(7 answers)
Closed 9 years ago.
I have a hash map and values in it. Now i want to set the values in the map as keys and keys as values. Can anyone suggest any idea?
My Map is
Map<String, String> col=new HashMap<String, String>();
col.put("one","four");
col.put("two","five");
col.put("three","Six");
Now i want to create an another map and put it in other way as i told above. ie,
Map<String, String> col2=new HashMap<String, String>();
col.put("five","one");
col.put("four","two");
col.put("Six","three");
Anybody has idea? Thanks
Like so:
Map<String, String> col2 = new HashMap<String, String>();
for (Map.Entry<String, String> e : col.entrySet()) {
col2.put(e.getValue(), e.getKey());
}
Assuming your values are unique in your hashmap, you can do like this.
// Get the value collection from the old HashMap
Collection<String> valueCollection = col.values();
Iterator<String> valueIterator = valueCollection.iterator();
HashMap<String, String> col1 = new HashMap<String, String>();
while(valueIterator.hasNext()){
String currentValue = valueIterator.next();
// Find the value in old HashMap
Iterator<String> keyIterator = col.keySet().iterator();
while(keyIterator.hasNext()){
String currentKey = keyIterator.next();
if (col.get(currentKey).equals(currentValue)){
// When found, put the value and key combination in new HashMap
col1.put(currentValue, currentKey);
break;
}
}
}
Create another Map and iterate through keys/values one by one and put in new Map. finally delete old one.
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());