Home > Enterprise >  Conditions in stream
Conditions in stream

Time:07-03

Here's my code

    public String marks(Double d){
    if (d>90)
        return "A";
    else if (90>=d&&d>=83)
        return "B";
    else if (83>d&&d>=75)
        return "C";
    else if (75>d&&d>=68)
        return "D";
    else if (68>d&&d>=60)
        return "E";
    else
        return "F";


}

public Map<Person, String> defineMarks(Stream<CourseResult> results) {
    return results.collect(Collectors.toMap(CourseResult::getPerson,x->marks(x.getTaskResults().values().stream().mapToDouble(Integer::doubleValue).average().orElse(0))));
}

And here's CourseResult class for reference.

public class CourseResult {
private final Person person;
private final Map<String, Integer> taskResults;

public CourseResult(final Person person, final Map<String, Integer> taskResults) {
    this.person = person;
    this.taskResults = taskResults;
}

public Person getPerson() {
    return person;
}

public Map<String, Integer> getTaskResults() {
    return taskResults;
}

}

So my defineMarks method returns a map of persons with marks they got for their respective scores. Can I somehow get those conditions into a stream instead of using a method like I did?

CodePudding user response:

Can I somehow get those conditions into a stream instead of using a method like I did?

You can move the logic of your marks method in to the stream and get rid of your marks method like below. But like others already mentioned in the comments, only because you can doesn't mean you should

public Map<Person, String> defineMarks(Stream<CourseResult> results) {
    return results.collect(
            Collectors.toMap(
                    CourseResult::getPerson,
                    x -> {
                        double avg = x.getTaskResults().values().stream().collect(Collectors.summarizingInt(Integer::intValue)).getAverage();
                        if(avg >  90) return "A";
                        if(avg >= 83) return "B";
                        if(avg >= 75) return "C";
                        if(avg >= 68) return "D";
                        if(avg >= 60) return "E";
                        else return "F";
                    }
            ));
}
  • Related