Hi Priyanka,
So in both cases, the problem is that the Comparator you are using is causing this confusion. So the max method takes a Comparator and uses that to compare each object with the other. The comparator is supposed to compare the two numbers, return a positive value is the first one is bigger or a negative value if the second one is bigger. So something like this:
But your comparator always returns the biggest value, so whenever it compares two numbers, it will always thinks the first number is bigger. So it will do the following:
Arrays.asList(3,4,6,9,2,5,7);
1. Compare 3 to 4, comparator will return 4, since it is a positive number the Stream thinks the first number i.e. 3 is bigger.
2. Compare 3 to 6, comparator will return 6, since it is a positive number the Stream thinks the first number i.e. 3 is bigger.
3. Compare 3 to 9, comparator will return 9, since it is a positive number the Stream thinks the first number i.e. 3 is bigger.
4. Compare 3 to 2, comparator will return 3, since it is a positive number the Stream thinks the first number i.e. 3 is bigger.
5. Compare 3 to 5, comparator will return 5, since it is a positive number the Stream thinks the first number i.e. 3 is bigger.
6. Compare 3 to 7, comparator will return 7, since it is a positive number the Stream thinks the first number i.e. 3 is bigger.
So due to the comparator you are passing, the stream thinks the first number is the biggest.