Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream API - is there standard method for processing each value in Map to different type?

Tags:

java

java-8

I learn Java 8 Lambda Expressions and stream API. In order to understand I try to make expression analog for SQL quesry:

select department, avg(salary) from employee group by department

for:

private static class Employee {
    public String name;
    public String department;
    public int salary;
}

Solution present in official tutorial:

empls.stream().collect(
    Collectors.groupingBy(
        x -> x.department,
        Collectors.averagingInt(x -> x.salary)))

Before I found this solution my strategy to calculate average with grouping:

Map<String, List<Employee>> tmp =
    empls.stream().collect(Collectors.groupingBy(x -> x.department));

and applying functor to each value. But in Map interface there are no method to transform value into different type. In my case reduce List to Double. Standard SE API provide only method replaceAll() that convert value to same type...

What Java 8 style method/trick/one-liner to convert Map value into different type? Worked like pseudo-code:

Map<K, V2> map2 = new HashMap<>();
for (Map.Entry<K, V1> entry : map1.entrySet()) {
     map2.add(entry.getKey(), Function<V1, V2>::apply(entry.getValue()));
 }
like image 715
gavenkoa Avatar asked Jul 27 '14 22:07

gavenkoa


People also ask

How does stream API works internally in Java 8?

Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

How many methods are there in the collection interface for generating a stream in Java 8?

With Java 8, Collection interface has two methods to generate a Stream.

Which method is used to create a stream source from values?

of(T…t) method can be used to create a stream with the specified t values, where t are the elements. This method returns a sequential Stream containing the t elements.

What is the purpose of map method of stream in Java 8?

Java 8 Stream's map method is intermediate operation and consumes single element forom input Stream and produces single element to output Stream. It simply used to convert Stream of one type to another.


1 Answers

You want:

Map<K, V2> map2 = 
    map1.entrySet().stream()
        .collect(toMap(Map.Entry::getKey, 
                       e -> f.apply(e.getValue()));

where f is a function from V to V2.

like image 165
Brian Goetz Avatar answered Oct 10 '22 16:10

Brian Goetz