I have an arraylist of Map type . I want to filter out null values from the list and find max and min values. The program is working fine except for null values.
ArrayList<Map<String, Float>> elements = new ArrayList<Map<String, Float>>();
Map<String, Float> element = new HashMap<String, Float>();
element.put("a", (float) 1.22);
element.put("b", (float) 1.33);
element.put("c", (float) 1.52);
element.put("d", (float) 1.452);
element.put("e", (float) 1.452);
Map<String, Float> element2 = new HashMap<String, Float>();
element2.put("a", (float) 1.2332);
element2.put("b", (float) 1.242);
element2.put("c", (float) 1.552);
element2.put("d", (float) 15.33);
element2.put("e",null);
elements.add(element);
elements.add(element1);
elements.add(element2);
System.out.println("Initial Mappings are: " + elements);
Map<String, Float> min = elements.stream()
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Math::min));
System.out.println(min);
Add a filter to the chain.
Map<String, Float> min = elements.stream()
.flatMap(m -> m.entrySet().stream())
.filter(entry -> entry.getValue() != null)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, Math::min));
You can use filter to filter null values and use Collectors.summarizingDouble to get min,max and average
Map<String, DoubleSummaryStatistics> res = elements.stream()
.flatMap(m -> m.entrySet().stream())
.filter(entry->Objects.nonNull(entry.getValue()) // check for null value
.collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.summarizingDouble(entry->entry.getValue())));
res.forEach((k,v)->System.out.println("Key : "+k+", Min : "+v.getMin()+", Max : "+v.getMax()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With