What are the uses of constructor reference in java 8

血红的双手。 提交于 2019-11-28 12:37:18
Holger

First of all, you should understand that constructor references are just a special form of method references. The point about method references is that they do not invoke the referenced method but provide a way to define a function which will invoke the method when being evaluated.

The linked article’s examples might not look that useful but that’s the general problem of short self-contained example code. It’s just the same as with the “hello world” program. It’s not more useful than typing the text “hello world” directly into the console but it’s not meant to be anyway. It’s purpose is to demonstrate the programming language.

As assylias has shown, there are use cases involving already existing functional interfaces using the JFC API.


Regarding the usefulness of a custom functional interface that’ll be used together with a constructor reference, you have to think about the reason to use (functional) interface in general: abstraction.

Since the purpose of an interface is to abstract the underlying operation, the use cases are the places where you do not want to perform an unconditional new SomeType(…) operation.

So one example is the commonly known Factory pattern where you define an interface to construct an object and implementing the factory via constructor reference is only one option out of the infinite possibilities.

Another important point are all kinds of Generic methods where the possibility to construct instances of the type, that is not known due to type erasure, is needed. They can be implemented via a function which is passed as parameter and whether one of the existing functional interfaces fits or a custom one is needed simply depends on the required number and types of parameters.

It's useful when you need to provide a constructor as a supplier or a function. Examples:

List<String> filtered = stringList.stream()
        .filter(s -> !s.isEmpty())
        .collect(Collectors.toCollection(ArrayList::new)); //() -> new ArrayList<> ()

Map<String, BigDecimal> numbersMap = new HashMap<>();
numbersMap.computeIfAbsent("2", BigDecimal::new); // s -> new BigDecimal(s)

someStream.toArray(Object[]::new); // i -> new Object[i]

etc.

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