How to convert HashMap to ArrayList in Java

1 Answer

0 votes
import java.util.Collection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

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);
        
        Set<String> keySet = hmp.keySet(); 
  
        // ArrayList of keys 
        ArrayList<String> ALKeys = new ArrayList<String>(keySet); 
  
        Collection<Integer> values = hmp.values(); 
  
        // ArrayList of values 
        ArrayList<Integer> ALValues = new ArrayList<>(values); 
  
        System.out.println(ALKeys); 
  
        System.out.println(ALValues); 
    }
}
        
        
        
        
/*
run:
        
[c#, rust, c++, python, java, c, php]
[1, 6, 2, 5, 4, 7, 3]

*/

 



answered Oct 8, 2023 by avibootz

Related questions

1 answer 200 views
1 answer 189 views
1 answer 141 views
141 views asked Nov 7, 2021 by avibootz
1 answer 167 views
...