Reputation: 4266
I've got a list List<String>
(list1
) and a function Integer foo(String s)
. Using the power of Java 8 I want to convert list1
to a List<Integer>
by applying foo
to each item of list1
. The following code works but has a little problem:
List<Integer> list2 = list1.stream().mapToInt(s -> foo(s)).boxed().collect(Collectors.toList());
When foo
returns null
for some element of list1
a NullPointerException
is thrown. Additionally my solution looks a little bit inconvenient. So is there a better one?
Upvotes: 2
Views: 116
Reputation: 37645
As an alternative to the answer already given, you can do this:
List<Integer> list2 = new ArrayList<>();
list1.forEach(s -> list2.add(foo(s)));
Upvotes: 1
Reputation: 47249
If you are mapping it to an Integer
, I don't see the need to use mapToInt
and then use boxed
.
Instead, you could simple use map
and then filter
to exclude the nulls.
List<Integer> list2 =
list1.stream()
.map(s -> foo(s))
.filter(Objects::nonNull)
.collect(Collectors.toList());
If you want to keep the nulls in the list, simply remove the filter
List<Integer> list2 =
list1.stream()
.map(s -> foo(s))
.collect(Collectors.toList());
Upvotes: 5