I have 2 ArrayLists:
private List<Client> clientList = new ArrayList<Client>();
private List<Client> sortedClientList = new ArrayList<Client>();
I sort clientList
like this:
clientList.sort(Comparator.comparing(Client::getScore));
What I want to do, is to "clone" all the content in the same order to the sortedClientList, but I'm doing something wrong.
I tried sortedClientList.add(clientList.sort(Comparator...
and sortedClientList.addAll(clientList.sort(Comparator...
however I get the error The method add(Client) in the type List<Client> is not applicable for the arguments (void)
My goal is to have a sorted list but in a separate object, thus sortedClientList
CodePudding user response:
Method sort
sorts the list and returns nothing (a.k.a. void
).
https://docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator-
CodePudding user response:
The method is of type void
meaning it doesn't return an object and therefore you cannot pass it as it if were an object.
clientList.sort(...)
this method sorts the elements of the clientList
, it does not create a copy of clientList
with the elements sorted.
What you're looking for is to make a sorted copy of the clientList
, a similar question is posed here: Sorted copy construction for ArrayList