Here in this code example we will go through the max, min and count operations which we can use as part of new functionality introduced by Java 8.
count() – Returns the count of elements in the stream.
max() – This method returns the max element of a stream. It returns an Optional. We should do a get() call on that to get the actual object.
min() – This method returns the max element of a stream. It returns an Optional. We should do a get() call on that to get the actual object.
import java.util.*;
import java.util.stream.*;
class Student {
private String name;
private int round;
private int points;
public Student(String name, int round, int points) {
super();
this.name = name;
this.round = round;
this.points = points;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRound() {
return round;
}
public void setRound(int round) {
this.round = round;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
public class Java8GroupByExample {
public static void main(String args[]) {
List<Integer> numList = Java8GroupByExample.getNumbersList();
Long count = numList.stream().count();
System.out.println("The count is "+count);
Integer max = numList.stream().max(Comparator.comparing(Integer::valueOf)).get();
System.out.println("The max is "+max);
Integer min = numList.stream().min(Comparator.comparing(Integer::valueOf)).get();
System.out.println("The min is "+min);
List<Student> studList = Java8GroupByExample.createStudList();
Comparator<Student> comparator = Comparator.comparing(Student::getPoints);
Student minStud = studList.stream().min(comparator).get();
System.out.println("The student with min points is "+minStud.getName());
Student maxStud = studList.stream().max(comparator).get();
System.out.println("The student with max points is "+maxStud.getName());
}
private static List<Integer> getNumbersList(){
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(12);
list.add(9);
list.add(15);
list.add(25);
list.add(4);
return list;
}
public static List<Student> createStudList()
{
List<Student> studList=new ArrayList<Student>();
Student s1=new Student("Nathan",1,500);
Student s2=new Student("Chris",1,1000);
Student s3=new Student("David",1,100);
Student s4=new Student("James",1,300);
Student s5=new Student("Mike",1,3000);
studList.add(s1);
studList.add(s2);
studList.add(s3);
studList.add(s4);
studList.add(s5);
return studList;
}
}
