In java 8+ are only single argument method reference permitted in a stream

  • A+
Category:Languages

Is it true to say that in a Stream in Java 8, you can only use method references that take a single argument (if you disallow wrapping the method reference with a method call)?

I assume so because in a stream at any time you are processing a single item.

Therefore:

  • Something::new (must refer to a single arg constructor)
  • this::doSomething (must take a single arg)
  • Something::doSomething (must take a single arg)

...when used in a Stream. Is this rule always true?

 


No, it's not. Some of the Stream methods take functional interfaces having a method with multiple arguments.

For example, Stream's sorted(Stream<T> Comparator<? super T> comparator) method, takes a Comparator, whose method has two arguments.

Here's an example of using a method reference - String::compareTo - of a method having two arguments:

System.out.println(Stream.of("a","d","c").sorted(String::compareTo).collect(Collectors.toList())); 

Stream's Optional<T> max(Comparator<? super T> comparator) method is another similar example.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: