Call constructor with parameter inside Java stream

2020-04-02 06:45发布

I want to call a constructor for MySortedSet that takes in a Comparator c as a parameter. How can I modify this to do so?

public MySortedSet<E> subSet(E fromElement, E toElement) {
     return list.stream()
            .filter(x -> (list.indexOf(x) <= list.indexOf(fromElement)
                    && list.indexOf(x) < list.indexOf(toElement)))
            .collect(Collectors.toCollection(MySortedSet<E> :: new));
}

1条回答
SAY GOODBYE
2楼-- · 2020-04-02 07:41

You can’t use method references if you want to pass additional captured values as parameters. You will have to use a lambda expression instead:

MySortedSet<E> :: new

=>

() -> new MySortedSet<E>(c)
查看更多
登录 后发表回答