Need to access multiple methods in order to compare objects

Blackburn :

After reading the Oracle docs I did not found what I am looking for. I have an object that it can be compared in different ways, but one of its attributes is a List. How can I compare based on the size of the that List attribute?

Comparator comparator = Comparator.comparing(Product::getCommentList::size);
List<Product> soldL = new LinkedList();
soldL.addAll(sold);
Collections.sort(soldL,comparator);

I tried the code above without success.

Naman :

You can simply use lambda and improve your existing code as :

Comparator<Product> comparator = Comparator.comparing(p -> p.getCommentList().size()); // type 'Product' bound
List<Product> soldL = new LinkedList<>(); // type inferred '<>'
soldL.addAll(sold);
soldL.sort(comparator); // use 'List.sort'

Edit: You can make use of the comparingInt instead of comparaing to avoid boxing as:

Comparator<Product> comparator = Comparator.comparingInt(p -> p.getCommentList().size()); 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=145430&siteId=1