Rasmond
Rasmond

Reputation: 512

How to create sublist based on condition in Java

I have a list of String

List<String> strings = new ArrayList<>(Arrays.asList("C", "C++", "Java"));

And now I want to create another list, which would contain all elements of strings that contain "C". So I believe that the condition would look like this:

(String a) -> a.contains("C");

What is the fastest and most clear way to do that?

Upvotes: 2

Views: 5090

Answers (1)

Jacob G.
Jacob G.

Reputation: 29710

I recommend streaming the List and then using Stream#filter to filter through any elements that contain the letter 'C':

List<String> filteredList = strings.stream()
        .filter(s -> s.contains("C"))
        .collect(Collectors.toList());

Printing filteredList will yield the following:

[C, C++]

Upvotes: 4

Related Questions