Home > Net >  Java reverse sort on list size
Java reverse sort on list size

Time:12-06

I have a simple problem. I have the following class:

public class PostCollection {

    private String name;
    private List<Post> posts;

    public PostCollection(String name, List<Post> posts) {
        this.name = name;
        this.posts = posts;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Post> getPosts() {
        return posts;
    }

    public void setPosts(List<Post> posts) {
        this.posts = posts;
    }
}

Then I have a List<PostCollection> which I want to reverse sort on list size, so the largest size comes first. To sort on list size from small to large I have this line:

allCollections = allCollections.stream().sorted(Comparator.comparing(c -> c.getPosts().size())).collect(Collectors.toList());

So I thought that the reverse sort was:

allCollections = allCollections.stream().sorted(Comparator.comparing(c -> c.getPosts().size()).reversed()).collect(Collectors.toList());

But that gives me the error:

Cannot resolve method 'getPosts' in 'Object'

on the method getPosts()....

What am I doing wrong?

CodePudding user response:

Explicitly stating the Comparator's type would solve the issue:

allCollections = 
    allCollections.stream()
                  .sorted(Comparator.comparing((PostCollection c) -> c.getPosts().size())
                                    .reversed())
                  .collect(Collectors.toList());

CodePudding user response:

The following will work. Notice <PostCollection, Integer> type specification to the comparing(..) method.

allCollections = allCollections.stream().sorted( Comparator.<PostCollection, Integer>comparing( c -> c.getPosts().size() ).reversed() ).collect( Collectors.toList() );

If you do not specify the actual parameters, the difficulty is that Comparator.comparing(..) takes a function with super boundary restrictions. Since you are passing a lambda and not an implementation class, this means it can return anything in the hierarchy from Comparator<Object> to Comparator<PostCollection>. So, at this point, the actual type cannot be fixed.

However, if you look at the code of Comparator.reversed(), it calls Collections.reverseOrder(Comparator<S>) which means that by the time it is called, the actual type of S in the Comparator returned by Comparator.comparing(..) should have been determined. This, as we saw, is not possible.

So, there is a need to specify the actual types intended/expected.

  • Related