Need to access multiple methods in order to compare objects

Viewed 55

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.

2 Answers

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()); 

You can simplify the comparison by implementing a method on Product that returns the size of the list (ex: public int getCommentListSize() { return commentList.size(); }).

So you can create a comparator this way:

Comparator comparator = Comparator.comparing(Product::getCommentListSize);

After that, you pass comparator to the sort method.

Related