7

What is the shortest way to express "get new List B from List A where condition" via a Java 8 lambda?

Say I have List<Integer> a = Arrays.asList(1, 2, 3, 4, 5) and I want a new List, B, where the value is > 3.

I've read through the new Collections Streams API, but I'm not convinced I have found the best way to do this, and don't want to taint the question with what is probably my less than perfect solution.

1

1 Answer 1

16
a.stream().filter(x -> x > 3).collect(Collectors.toList()); 

Java 16 solution

It can be written in a further shorter form in JDK 16 which includes a toList() method directly on Stream instances.

a.stream().filter(x -> x > 3).toList(); 
Sign up to request clarification or add additional context in comments.

1 Comment

I just love SO - one answer; and straight from one of the Guava guys! Does it get any better?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.