We can apply comparable & comparator both on integers, as like below:
List<Integer> intList1 = Arrays.asList(1,9,4,8,2,3,7,4,5);
Optional<Integer> val1 = intList1.stream().sorted((a, b) -> a.compareTo(b)).skip(1).findFirst();
Optional<Integer> val2 = intList1.stream().sorted((a,b) -> a >= b ? 1 : -1).skip(1).findFirst();
Same I am trying to apply on integer getting from String.length(), like below:
List<String> strList = Arrays.asList("ab", "abc", "abcd");
Optional<String> strVal1 = strList.stream().sorted((a, b) -> a.length() >= b.length() ? 1 : -1 )
.skip(1).findFirst();
System.out.println(strVal1.get());
Optional<String> strVal2 = strList.stream().sorted((a, b) -> a.length().compareTo(a.length()))
.skip(1).findFirst();
System.out.println(strVal2.get());
Question: Showing error while applying compareTo() on a.length() which returns integer only for variable strVal2
What did you try:
Tried with comparator() and comparable() on custom objects also.
what were you expecting:
Explanation for such behaviour.