-1

I have to iterate the HashMap object list. if the map object value is true then I have to return that entry to one map Hash object using java 8 stream API


public class HashMapCheck {
    static Map<String, Boolean> map;
    static Map<String, Boolean> map2;
    static List<Map> objMap;

    public static void main(String args[]) {
        map = new HashMap<String, Boolean>();
        map.put("1", true);
        map.put("2", false);

        map2 = new HashMap<String, Boolean>();
        map2.put("4", true);
        map2.put("5", true);
        objMap = new ArrayList<Map>();
        objMap.add(map);
        objMap.add(map2);

        //Iterate
    }
}
  • Can you share the expected result for the data you have in your example? – Mureinik Sep 19 '20 at 17:35
  • Does this answer your question? [How to filter a map by its values in Java 8?](https://stackoverflow.com/questions/33459961/how-to-filter-a-map-by-its-values-in-java-8) – Curiosa Globunznik Sep 19 '20 at 17:37
  • `List` uses a *raw* map. Don't do that. [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/q/2770321/5221149) – Andreas Sep 19 '20 at 18:08
  • How would you do it without using Java 8 Streams? Which part of using Streams instead is troubling you? – Andreas Sep 19 '20 at 18:10
  • Why must you use streams? Is this homework? Or is it that you’ve heard it’s cool to use streams in your code? – Abhijit Sarkar Sep 19 '20 at 18:54
  • @AbhijitSarkar Yes using streams,the code will be very optimized instead using normal for loop and lines of code..etc – Sriram Kumar Sep 21 '20 at 13:10

1 Answers1

0

I'm not an expert with Java streams, so maybe this is not the minimal solution, but here's what I came up with using streams to get what I think you want:

public class HashMapCheck {
    static Map<String, Boolean> map;
    static Map<String, Boolean> map2;
    static List<Map<String, Boolean>> objMap;

    public static void main(String[] args) {

        map = new HashMap<>();
        map.put("1", true);
        map.put("2", false);

        map2 = new HashMap<>();
        map2.put("4", true);
        map2.put("5", true);
        objMap = new ArrayList<>();
        objMap.add(map);
        objMap.add(map2);

        Map<String, Boolean> result = objMap.stream().flatMap(x -> x.entrySet().stream()).filter(Map.Entry::getValue).
                collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

        System.out.println(result);

    }
}

Result:

{1=true, 4=true, 5=true}
CryptoFool
  • 21,719
  • 5
  • 26
  • 44