What does “an Arbitrary Object of a Particular Type” mean in java 8?

The example given from the Oracle Doc linked is:

String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" };
Arrays.sort(stringArray, String::compareToIgnoreCase);

The lambda equivalent of

 String::compareToIgnoreCase

would be

(String a, String b) -> a.compareToIgnoreCase(b)

The Arrays.sort() method is looking for a comparator as its second argument (in this example). Passing String::compareToIgnoreCase creates a comparator with a.compareToIgnoreCase(b) as the compare method’s body. You then ask well what’s a and b. The first argument for the compare method becomes a and the second b. Those are the arbitrary objects, of the type String (the particular type).

Don’t understand?

  • Make sure you know what a comparator is and how to implement it.
  • Know what a functional interface is and how it affects lambdas in Java.
  • A comparator is a functional interface that’s why the method reference becomes the body of the compare method inside the comparator object.
  • Read the source below for another example at the bottom of the page.

Read more at the source:
http://moandjiezana.com/blog/2014/understanding-method-references/

Leave a Comment