I have the following Problem. I have an array of Strings representing email addresses and i want to convert the strings to another Type. To do this i am using Java Streams.
final List<String> recipientsStrings = Arrays.asList("test@mail.com", "test2@mail.com")
final InternetAddress[] to = (InternetAddress[]) recipientsStrings
.stream()
.map(this::createInternetAddress)
.toArray();
and the signature of createInternetAddress is:
private InternetAddress createInternetAddress(final String address)
The Problem is, that the map function is throwing a java.lang.TypeNotPresentException. The strange thing is, that if i write a lambda function instead of a method reference it works. So my question is what is the difference between the following pieces of code.
.map(this::createInternetAddress)
and
.map(mail -> this.createInternetAddress(mail))
With both signatures, I got this error:
Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [LInternetAddress; ([Ljava.lang.Object; is in module java.base of loader 'bootstrap'; [LInternetAddress; is in unnamed module of loader 'app')
Either lambda function or method reference is equivalent, your issue is with the casting (InternetAddress[])
, to solve this you can simply use:
final InternetAddress[] to = recipientsStrings
.stream()
.map(this::createInternetAddress)
.toArray(InternetAddress[]::new);