Page 1 of 1
About Question enthuware.ocpjp.v8.2.1762 :
Posted: Tue May 17, 2016 8:39 am
by RAZER-KIEV
.sorted((a, b)->a.getId().compareTo(b.getId()))
This option creates a Comparator using a lambda expression that compares two Item objects for their id attribute. Syntactically, this option is correct except but we need to sort by name instead of id.
Good day!
Actually we can sort it by Id too. Just by replacing
".sorted((a, b)->b.getId().compareTo(a.getId())".
Re: About Question enthuware.ocpjp.v8.2.1762 :
Posted: Tue May 17, 2016 10:25 pm
by admin
Yes, that is correct as well (although not one of the options).
HTH,
Paul.
Re: About Question enthuware.ocpjp.v8.2.1762 :
Posted: Thu Jun 28, 2018 10:15 am
by anojer8
.sorted((a, b)->a.getId().compareTo(b.getId()))
you use a compareTo() for a Comparator, why not the compare()?
https://docs.oracle.com/javase/8/docs/a ... mpare-T-T-
Re: About Question enthuware.ocpjp.v8.2.1762 :
Posted: Thu Jun 28, 2018 12:36 pm
by admin
You could probably use compareTo in some way but in what way exactly do you mean? It is not necessary that a question will include all possible ways to do something.
Re: About Question enthuware.ocpjp.v8.2.1762 :
Posted: Thu Jun 28, 2018 1:17 pm
by anojer8
admin wrote: ↑Thu Jun 28, 2018 12:36 pm
You could probably use compareTo in some way but in what way exactly do you mean? It is not necessary that a question will include all possible ways to do something.
Ok, of course I understand that. I just was wondering why it is possible to use the compareTo() although you use a Comparator. I thought with a Comparator you must use a compare()
Re: About Question enthuware.ocpjp.v8.2.1762 :
Posted: Thu Jun 28, 2018 2:15 pm
by admin
I am assuming that you are talking about option 1. Stream class's sorted(Comparator ) method requires a Comparator. Comparator is a functional interface that can be implemented using a method that takes two String parameters and returns a boolean. The lambda expression used in this option is used to build such a method. The body of this method uses String's compareTo method. This is possible because String implements Comparable and so has a compareTo method.
In other words, a Comparator's compare method is being built here using String's compareTo method. So we are not calling compareTo on a Comparator, we are calling compareTo on a String.
Re: About Question enthuware.ocpjp.v8.2.1762 :
Posted: Thu Jun 28, 2018 2:36 pm
by anojer8
Thanks! It's clear now.