2

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?

2
  • 5
    strings.stream().filter(t -> t.contains("C")).collect(Collectors.toList()) Commented May 27, 2019 at 19:40
  • Another possibility: strings.removeIf(a -> !a.contains("C")) (Note that this modifies the strings List itself.) Commented May 28, 2019 at 0:09

1 Answer 1

4

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++]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.