2

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);
2
  • null map or a null element in a map? Your example does not contain any nulls Commented Dec 24, 2019 at 4:04
  • You must try and ensure that your Map doesn't allow null writes such as element2.put("e",null); in reality. This was corrected in JDK itself with Map.ofimplementation in Java-9 as well. Commented Dec 24, 2019 at 4:29

2 Answers 2

5

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));
Sign up to request clarification or add additional context in comments.

Comments

3

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()));

1 Comment

The question doesn't really focus around using **SummaryStatistics, but a good suggestion, though the actual answer already exists.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.