• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

Question on stream.max method

 
Ranch Hand
Posts: 127
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Please observe below code:



Lines with labels 1 and 3 are producing result 9
Lines with labels 2 and 4 are producing result 3.

Two questions here:

1. Why lines with labels 1 and 4 are producing result differently when same lamba is passed?
2. Why lines with labels 2 and 3 are producing result differently? what is so different about comparing a with b versus comparing with Math.max?

Could someone clarify what is happening here?

Thanks, Raaghu
 
Bartender
Posts: 2236
63
IntelliJ IDE Firefox Browser Spring Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Math.max returns a greater one of two numbers.
In your example this number is used in place when the result of Comparator.compare() is expected.
This might lead to strange results.

We have 3, 4, 6...
The goal is to find the biggest one based on a comparator that uses Math.max.

Comparator.compare(3, 4) will be called. It will call Math.max(3, 4). That returns 4. A positive value. Our compare() method returned a positive value. This means the first argument is bigger.

The biggest number found so far is 3.

We need to take next one.

Comparator.compare(3, 6) will be called. It will call Math.max(3, 6). That returns 6. A positive value. Our compare() method returned a positive value. This means the first argument is bigger.

The biggest number found so far is 3.

We need to take next one....
 
We must storm this mad man's lab and destroy his villanous bomb! Are you with me tiny ad?
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic