java stream List<Map<String,Double>> need average based on the string

java stream map
java stream filter
when to use java streams
java stream foreach
java streams explained
java stream anymatch
java 8 streams in depth
types of streams in java

I need the average of the list

    List<Measurement> measurements = new ArrayList<>();

    Measurement m1 = new Measurement();
    Map<String,Double> map1 = new HashMap<>();
    map1.put("age",18.0);
    map1.put("score",88.0);
    map1.put("rating",5.0);
    m1.setMetric(map1);

    Measurement m2 = new Measurement();
    Map<String,Double> map2 = new HashMap<>();
    map2.put("age",21.0);
    map2.put("score",null);
    map2.put("rating",23.0);
    m2.setMetric(map2);

    Measurement m3 = new Measurement();
    Map<String,Double> map3 = new HashMap<>();
    map3.put("age",31.0);
    map3.put("score",32.0);
    map3.put("rating",null );
    m3.setMetric(map3);

    measurements.add(m1);
    measurements.add(m2);
    measurements.add(m3);

How do I get the average Age for the above list of maps. Also Average Score by ignoring the null values.

Any help would be really appreciated. I am struggling to fix since 3 days. Thank you in advance.

for such Measurement class:

class Measurement {

    Map<String, Double> map;

    public void setMetric(Map<String, Double> map) {
        this.map = map;
    }
}
How to find avarage "age" (using stream):
Double averageAge = measurements.stream()
        .collect(Collectors.averagingDouble(node -> node.map.getOrDefault("age", 0D)));

And stream for nullable "score":

How to find avarage "age" (using stream) with null check:
Double averageAge = measurements.stream()
        .filter(node -> node.map.get("score") != null)
        .collect(Collectors.averagingDouble(node -> node.map.getOrDefault("score", 0D)));

In above code you have node.map where map is field form class. Can be replaced with getMap() or different method returning value (which you are set by setMetric())

How to find avarage "age" (using loop):
Double average = 0D;
for (Measurement measure : measurements) {
    average += measure.map.getOrDefault("age", 0D);
}
average /= measurements.size();
How to find avarage "score" (using loop) with null check:
Double average = 0D;
int counter = 0;
for (Measurement measure : measurements) {
    if (measure.map.get("score") != null) {
        average += measure.map.getOrDefault("score", 0D);
        counter++;
    }
}
average /= counter;
How to find the smallest "score" (using loop) with null check:
Double min = Double.MAX_VALUE;

for (Measurement measure : measurements) {
    Double score = measure.map.get("score");
    if (score != null && score < min) {
        min = score;
    }
}

System.out.println(min);
How to find the biggest "age" (using streams)
Double max = measurements.stream()
        .filter(node -> node.map.get("score") != null)
        .mapToDouble(node -> node.map.get("score"))
        .max()
        .orElse(0.0);

A Guide to Streams in Java 8: In-Depth Tutorial With Examples, private static List<Employee> empList = Arrays.asList(arrayOfEmps); empList. stream();. Note that Java 8 added a new stream() method to the� Convert stream to list for filtered elements. Sometimes we need to find specific items in stream and then add only those elements to list. Here, we can use Stream.filter () method to pass a predicate which will return only those elements who match the pre-condition. Convert stream to list - filtered elements.

You can get an average of age as:

Double averageAge = measurements.stream()
        .flatMap(a -> a.getMetric().entrySet().stream())
        .filter(a -> a.getKey().equals("age"))
        .mapToDouble(Map.Entry::getValue)
        .average()
        .orElse(Double.NaN);

and similarly, averaging score would require an additional filter condition to exclude null values.

The Java 8 Stream API Tutorial, The Java 8 Stream API Tutorial � Stream<String> streamEmpty = Stream. � public Stream<String> streamOf(List<String> list) { � Collection<String>� output. java python node. Yet another example, filter a number 3 and convert it to a List. Java8Example2.java. package com.mkyong.java8; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class Java8Example2 { public static void main(String[] args) { Stream<Integer> number = Stream.of(1, 2, 3, 4, 5); List<Integer> result2 = number.filter(x -> x != 3).collect(Collectors.toList()); result2.forEach(x -> System.out.println(x)); } }

You can compute the average values for each map key using:

Map<String, Double> result = Stream.of(m1, m2, m3)
        .flatMap(m -> m.getMap1().entrySet().stream()
                       .filter(e -> e.getValue() != null))
        .collect(Collectors.groupingBy(e -> e.getKey(), 
                Collectors.averagingDouble(e -> e.getValue())));

And the output for your test data is {score=60.0, rating=14.0, age=23.333333333333332}

Package java.util.stream, Since the list was modified before the terminal collect operation commenced the result will be a string of "one two three". All the streams returned from JDK� List: [GeeksForGeeks, A computer portal, for Geeks] Stream from List: [GeeksForGeeks, A computer portal, for Geeks] Filter Stream using a Predicate : The Functional Interface Predicate is defined in the java.util.Function package and can therefore be used as the assignment target for a lambda expression or method reference.

Java 8 - Streams, parallelStream() − Returns a parallel Stream considering collection as its source . List<String> strings = Arrays. The object C contains an attribute name that i want to use to filter using java 8. how to write the code below in java 8 using streams to avoid nested loop : C c1 = null;String name = "name1"for (A a: listOfAObjects) { for (B b: a.getList()) { for (C c: b.getPr()) { if (c.getName().equalsIgnoreCase(name)) { c1= c; break; } } }}

Stream In Java, Stream In Java � collect: The collect method is used to return the result of the intermediate operations performed on the stream. List number =� Streams filter () and collect () 1.1 Before Java 8, filter a List like this : BeforeJava8.java. package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class BeforeJava8 { public static void main(String[] args) { List<String> lines = Arrays.asList("spring", "node", "mkyong"); List<String> result = getFilterOutput(lines, "mkyong"); for (String temp : result) { System.out.println(temp); //output : spring, node } } private static List<String>

Java 8 Stream - Java Stream Example, Java Streams can be defined as a sequence of elements from a source that supports Convert Stream to List – Stream.collect( Collectors. Note: you can statically import java.util.stream.Collectors.joining if you prefer just typing "joining". In Java 7. For old times' sake, let’s have a look at the Java 7 implementation:

Comments
  • Can you share the Measurement object?
  • Thank you a lot for your quick response. :) really appreciated. Also I need the average for 'score' which has null values. I am getting null pointer for that. Please help me in this
  • what I need is - If there is a null; just ignore that; and not to add in the average. Ex: value 1:10, value 2: null, Value 3: 30 - then the average is (value1+value3)/2. Not the (value1+value3)/3
  • This suits to me better; but If wanted to have max or min value instead of average? Pleases let me know
  • @Hruday Added min and max.
  • I guess you don't have to use filter. It may look like .mapToDouble(map -> map.get("age"))
  • @Ruslan made it general considering the case for null values of scores in another computation.
  • If you want to avoid nulls, just add a .filter(Objects::nonNull).
  • You can use .map(a -> a.getMetric()) .flatMapToDouble(m -> m.containsKey("age")? DoubleStream.of(m.get("age")): DoubleStream.empty()). Further, there is no reason to box the result into a Double instead of just using double.
  • Thank you; What if I wanted to have Max value instead of average? Could you please let me know
  • @Hruday You can use Collectors.maxBy instead of averagingDouble. But there would be some cleanup to get rid of the Optional in values.
  • IMHO, the code becomes more readable when moving the .filter(e -> e.getValue() != null) from the function passed to flatMap to a subsequent step of the other stream.