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 107 views
3 answers 143 views
2 answers 95 views
1 answer 91 views
2 answers 180 views
...