When parameter types in lambda expressions required

Currently, I see no differences in the following Java 8 lambda expressions:

Parameter Types :

Arrays.sort(strArray, (String s1, String s2) -> s2.length() - s1.length());

Types of parameters omitted :

Arrays.sort(strArray, (s1, s2) -> s2.length() - s1.length());

EDIT: In general, what are the pros and cons for specifying parameter types in Java 8 lambda expressions? And when do you need to specify?

I was thinking of several possible reasons (but I'm sure there are more):

  • additional security checks when specified
  • improved code readability
+4
source share
3 answers

. , . , , ; import static java.util.Comparator.comparingInt Arrays.sort(strArray, comparingInt(String::length)). ; ​​ .

+6

- . (strArray):

public static <T> void sort(T[] a, Comparator<? super T> c) {
} 

generics, .

lambda :

<R> Stream<R> map(Function<? super T, ? extends R> mapper);
T reduce(T identity, BinaryOperator<T> accumulator);
...

, , .

+1

, @louis-wasserman , , :

// DOES NOT compile
Arrays.sort(array, Comparator.comparingInts(str -> str.length()).reversed());

// DOES compile
Arrays.sort(array, Comparator.comparingInts((String str) -> str.length()).reversed());

As I understand it, it Comparator.reversed()requires a kind of contract regarding how the collection is organized at will. Without knowing the type str, he will not know the type of return .length(), thereby violating this contract.

+1
source

Source: https://habr.com/ru/post/1612103/


All Articles