Getting Min and Max values from a Stream in Java 8 is not a big deal, here we will see how it can be done.
Getting Min and Max values from a Stream:
Here are our use cases to get min and max values from the stream.
Usecases:
Usecase
// Numbers
Collection<Integer> elements = Arrays.asList(1,2,3,4,5);
Min = 1
Max = 5
//Strings
Collection<String> strings = Arrays.asList("a1","a2","a3","a4");
Min = a1
max = a4
// Objects
Collection<Student> students = Arrays.asList(new Student("Chandra",30),new Student("Rahul",25)
,new Student("Robert",20));
Younger = Robert
Elder = Chandra
Min and Max values from a Stream (Numbers):
Finding min and max numbers from an integer stream using stream().min() and stream().max() methods.
// Numbers
Collection<Integer> elements = Arrays.asList(1,2,3,4,5);
Integer min = elements.stream().min(Integer::compareTo).get();
Integer max = elements.stream().max(Integer::compareTo).get();
System.out.println("Min value : "+min);
System.out.println("Max value : "+max);
Output:
Terminal
Min value : 1
Max value : 5
Min and Max values from a Stream (Strings):
We can even get the min and max values for string; it internally compares the ASCII values.
// Strings
Collection<String> strings = Arrays.asList("a1","a2","a3","a4");
String min_string = strings.stream().min(String::compareTo).get();
String max_string = strings.stream().max(String::compareTo).get();
System.out.println("Min value : "+min_string);
System.out.println("Max value : "+max_string);
Output:
Terminal
Min value : a1
Max value : a4
Min and Max values from Stream (Objects):
Finding the min and max ages from a list of student objects. Create a Student object.
Student.java
public class Student{
private String name;
private Integer age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
Finding elder and younger students based on age.
// Objects
Collection<Student> students = Arrays.asList(new Student("Chandra",30),new Student("Rahul",25)
,new Student("Robert",20));
Student younger = students.stream().min((s1,s2)->s1.getAge().compareTo(s2.getAge())).get();
Student elder = students.stream().max((s1,s2)->s1.getAge().compareTo(s2.getAge())).get();
System.out.println("Younger is : "+younger.getName());
System.out.println("Elder is : "+elder.getName());
Output:
Terminal
Younger is : Robert
Elder is : Chandra
References:
Happy Learning 🙂