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()));
}
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.
With Java 8, Collection interface has two methods to generate a Stream.
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.
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.
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.
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