How to sort HashMap by key in ascending order Java

2 Answers

0 votes
import java.util.stream.Collectors;
import java.util.LinkedHashMap;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
  
public class MyClass {
    public static void main(String args[]) {
        HashMap<String, Integer> hmp = new HashMap<String, Integer>();
   
        hmp.put("java", 4);
        hmp.put("c++", 2);
        hmp.put("c", 7);
        hmp.put("python", 5);
        hmp.put("rust", 6);
        hmp.put("c#", 1);
        hmp.put("php", 3);
           
        LinkedHashMap<String, Integer> ascendingSortedMap = hmp.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (oldKey, newKey) -> oldKey, LinkedHashMap::new));

        System.out.println(ascendingSortedMap);
 
    }
}
       
       
       
       
/*
run:
       
{c=7, c#=1, c++=2, java=4, php=3, python=5, rust=6}
       
*/

 

 



answered Apr 29, 2023 by avibootz
0 votes
import java.util.HashMap;
import java.util.TreeMap;
   
public class MyClass {
    public static void main(String args[]) {
        HashMap<String, Integer> hmp = new HashMap<String, Integer>();
    
        hmp.put("java", 4);
        hmp.put("c++", 2);
        hmp.put("c", 7);
        hmp.put("python", 5);
        hmp.put("rust", 6);
        hmp.put("c#", 1);
        hmp.put("php", 3);
            
        TreeMap<String, Integer> tm = new TreeMap<>(hmp);
        
        System.out.println(tm);
  
    }
}
        
        
        
        
/*
run:
        
{c=7, c#=1, c++=2, java=4, php=3, python=5, rust=6}
        
*/

 



answered Apr 29, 2023 by avibootz

Related questions

1 answer 93 views
1 answer 95 views
1 answer 89 views
2 answers 150 views
1 answer 162 views
1 answer 140 views
...