Call constructor with parameter inside Java stream with lambda

浪尽此生 提交于 2019-12-04 03:02:03

问题


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:


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)


来源:https://stackoverflow.com/questions/26783788/call-constructor-with-parameter-inside-java-stream-with-lambda

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!