I'm learning about streams and I'm trying to map a test score to a letter grade using a stream. I think I'm close but I can't figure out the code to map it. The part that I'm hung up on is the Map at the end of the code. Here's the code that I have.
import java.util.ArrayList;
import java.util.Arrays;
import static java.util.Collections.list;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
public class LetterGrades {
public static void main(String[] args) {
List<String> gradeMap = new ArrayList<>();
GradeBook[] grades = {
new GradeBook(90, "A"),
new GradeBook(80, "B"),
new GradeBook(70, "C"),
new GradeBook(60, "D"),
new GradeBook(0, "F")};
List<GradeBook> list = Arrays.asList(grades);
// gradeMap.add("A");
// gradeMap.add("B");
// gradeMap.add("C");
// gradeMap.add("D");
// gradeMap.add("F");
//List<Integer> grades = new ArrayList<Integer>();
// grades.add(94);
// grades.add(85);
// grades.add(91);
// grades.add(100);
// grades.stream()
// .forEach(System.out::println);
Map<String, Integer> grade = list.stream().
collect(Collectors.groupingBy(GradeBook::getLetterGrade,
Collectors.joining(GradeBook::getScore)));
System.out.println(grade);
}
}
You can simply use Collectors.toMap()
:
Map<String, Integer> grade = list.stream().collect(
Collectors.toMap(GradeBook::getLetterGrade, GradeBook::getScore)
);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.