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,939 questions

51,876 answers

573 users

How to filter a map in Java

2 Answers

0 votes
import java.util.Map;
import java.util.HashMap;

public class MyClass
{
    public static void main(String[] args)
    {
        Map<String, Integer> hm = new HashMap();
         
        hm.put("java", 2);
        hm.put("python", 5);
        hm.put("c", 1);
        hm.put("c++", 3);
        hm.put("php", 6);
        hm.put("cobol", 8);
 
        Map<String, Integer> filteredMap = new HashMap<>();

        for (Map.Entry<String, Integer> entry: hm.entrySet()) {
            if (entry.getKey().startsWith("c")) {
                filteredMap.put(entry.getKey(), entry.getValue());
            }
        }
 
        System.out.println(filteredMap);
    }
}




/*
run:

{c++=3, c=1, cobol=8}

*/

 



answered Mar 20, 2023 by avibootz
0 votes
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;

public class MyClass
{
    public static void main(String[] args)
    {
        Map<String, Integer> hm = new HashMap();
         
        hm.put("java", 2);
        hm.put("python", 5);
        hm.put("c", 1);
        hm.put("c++", 3);
        hm.put("php", 6);
        hm.put("cobol", 8);
 
        String filteredMap = hm.entrySet()
                                .stream()
                                .filter(entry -> entry.getKey().startsWith("c"))
                                .map(Map.Entry::toString)
                                .collect(Collectors.joining(", ", "{", "}"));
 
        System.out.println(filteredMap);
    }
}




/*
run:

{c++=3, c=1, cobol=8}

*/

 



answered Mar 20, 2023 by avibootz

Related questions

1 answer 74 views
3 answers 106 views
2 answers 66 views
1 answer 66 views
2 answers 140 views
...