First, let’s defined the Java Bean we’ll use to represent something – a Student. Then, we’ll use Java Stream methods – Min and Max – to get the Minimum and Maximum values, respectively.
[wp_ad_camp_1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | package com.turreta.stream.minmax; import static org.junit.Assert.assertEquals; import java.util.Arrays; import java.util.Comparator; import java.util.List; import org.junit.Test; public class MinMaxTest { static class Student { private String name; private int grade; public Student(String name, int grade) { super(); this.name = name; this.grade = grade; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getGrade() { return grade; } public void setGrade(int grade) { this.grade = grade; } } @Test public void testMin() { List<Student> allStudents = Arrays.asList(new Student("Kulas", 80), new Student("George", 81), new Student("John", 75)); Student highest = allStudents.stream().min(Comparator.comparing(s -> s.getGrade())).get(); // George is the second Student object in the list assertEquals(allStudents.get(2).getGrade(), highest.getGrade()); } @Test public void testMax() { List<Student> allStudents = Arrays.asList(new Student("Kulas", 80), new Student("George", 81), new Student("John", 75)); Student highest = allStudents.stream().max(Comparator.comparing(s -> s.getGrade())).get(); // Kulas is the first Student object in the list assertEquals(allStudents.get(1).getGrade(), highest.getGrade()); } } |
We could create different codes that perform the same thing but why this is the most easy and convenient way to find out the min
and max
values.
[wp_ad_camp_5]