I have this following code snippet
    // List of persons with name and age
    List<Person> persons = new ArrayList<>();       
    // Adding 10,000 objects
    for(int i = 0 ; i < 10000 ; i ++) {
        Person p = new Person();
        p.setName("Person " + i);
        p.setAge(i);
        persons.add(p);
    }
    long time1 = System.nanoTime();
    System.out.println("Time before steram.reduce()" + time1);
    Optional<Person> o1 = Optional<Person> o1 = persons.stream().reduce(BinaryOperator.maxBy(Comparator.comparingInt(p -> p.getAge())));
    long time2 = System.nanoTime();
    System.out.println(o1.get() + "\nTime after stream.reduce() " + time2);
    System.out.println("**** Rough execution time for stream.reduce() : " + (time2 - time1) + " nano secs");
    long time3 = System.nanoTime();
    System.out.println("Time before stream.max() " + time3);
    Optional<Person> o2 = persons.stream().max((p01, p02) -> p01.getAge() - p02.getAge());
    long time4 = System.nanoTime();
    System.out.println(o2.get() + "\nTime after stream.max() " + time4);
    System.out.println("**** Rough execution time for stream.max() : " + (time4 - time3) + " nano secs");
While this might not be the ideal way to figure out execution time, basically what I am trying to do here is find the oldest Person and print out the time it took to find it out using stream.reduce() vs stream.max().
Output
Time before steram.reduce()8834253431112
[ Person 9999, 9999]
Time after stream.reduce() 8834346269743
**** Rough execution time for stream.reduce() : 92838631 nano secs
Time before stream.max() 8834346687875
[ Person 9999, 9999]
Time after stream.max() 8834350117000
**** Rough execution time for stream.max() : 3429125 nano secs
P.S. I have ran this code multiple times changing the order of stream.max() and stream.reduce() and found out that stream.reduce() takes significantly more time to produce the output than stream.max().
So is stream.max() always faster than stream.reduce()? If yes then, when should we use stream.reduce()?
 
     
    