Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,914 questions

51,847 answers

573 users

How to convert HashMap to List in Java

1 Answer

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

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", 6);
        hmp.put("python", 5);
        hmp.put("c#", 1);
        hmp.put("php", 3);
        
        System.out.println("HashMap Size : "  + hmp.size());

        
        Set<String> keySet = hmp.keySet();
        List<String> al_keys = new ArrayList<String>(keySet);
        
        System.out.println("ArrayList keys Size: " + al_keys.size());

        System.out.println("HashMap keys from al_keys: ");
        for (String key : al_keys) {
            System.out.println(key);
        }

        
        Collection<Integer> values = hmp.values();
        List<Integer> al_values = new ArrayList<Integer>(values);
        
        System.out.println("ArrayList values Size: " + al_values.size());

        System.out.println("HashMap values from al_values:");
        for (Integer value : al_values) {
            System.out.println(value);
        }

        Set<Entry<String, Integer>> set = hmp.entrySet();
        List<Entry<String, Integer>> al_key_value = new ArrayList<>(set);
        
        Iterator<Entry<String, Integer>> it = al_key_value.iterator();
        
        while (it.hasNext()) {
            Entry<String, Integer> entry = it.next();
            System.out.println(entry);
        }
    }
}
    
    
    
    
/*
run:
    
HashMap Size : 6
ArrayList keys Size: 6
HashMap keys from al_keys: 
c#
c++
python
java
c
php
ArrayList values Size: 6
HashMap values from al_values:
1
2
5
4
6
3
c#=1
c++=2
python=5
java=4
c=6
php=3
    
*/

 



answered Nov 7, 2021 by avibootz

Related questions

1 answer 136 views
1 answer 94 views
4 answers 206 views
2 answers 141 views
1 answer 101 views
101 views asked Oct 24, 2023 by avibootz
...