Java Stream collect to map via Collectors with two lambda expressions
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Language[] langArray = { // new Language("CSS", 55555,"Client"), // new Language("HTML", 66666,"Client"), // new Language("Java", 44444.5,"Server"), // new Language("Javascript", 77777.77,"Client"), // new Language("C++", 88888,"Server"), // new Language("C", 33333,"Server"), // new Language("SQL", 99999.4,"Server") };// List<Language> langList = Arrays.asList(langArray); langList.stream().forEach(System.out::println); Map<String, Double> map = langList//from w w w.j a va2 s . co m .stream() .collect(Collectors.toMap(Language::getType, p -> 1D, (oldCount, newCount) -> newCount+oldCount)); System.out.println(map); } } class Language { private String firstName; private double salary; private String type; public Language(String firstName, double salary, String t) { this.firstName = firstName; this.salary = salary; this.type = t; } public String getType() { return this.type; } public String getFirstName() { return firstName; } public double getSalary() { return salary; } @Override public String toString() { return String.format("%-20s %8.2f", getFirstName(), getSalary()); } }
The following code get the highest earner by type.
import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { Language[] langArray = { // new Language("CSS", 55555,"Client"), // new Language("HTML", 66666,"Client"), // new Language("Java", 44444.5,"Server"), // new Language("Javascript", 77777.77,"Client"), // new Language("C++", 88888,"Server"), // new Language("C", 33333,"Server"), // new Language("SQL", 99999.4,"Server") };// List<Language> langList = Arrays.asList(langArray); langList.stream().forEach(System.out::println); Map<String, Language> map = langList/*from w w w . j a va2s . co m*/ .stream() .collect(Collectors.toMap(Language::getType, Function.identity(), (a, a2) -> a2.getSalary() > a.getSalary() ? a : a2)); System.out.println(map); } } class Language { private String firstName; private double salary; private String type; public Language(String firstName, double salary, String t) { this.firstName = firstName; this.salary = salary; this.type = t; } public String getType() { return this.type; } public String getFirstName() { return firstName; } public double getSalary() { return salary; } @Override public String toString() { return String.format("%-20s %8.2f", getFirstName(), getSalary()); } }