1

I am trying to create a list from another list, such as:

List<String> namesOfLotion = List.of("Alexander Almond & Honey Moisturiser", "Max honey and almond moisturiser", "Mikhail Almond and Talc", "Mikhail Natural Almond Moisturizer", "Tigran Aloe Isolani", "Vassily Aloe Attack", "Vassily New aloe Attack");

From there I want to get all the names, which contains 'Aloe'

for which I am using following logic:

List<String> aloeLotion = trendyList.stream().anyMatch(str -> str.trim().equals("Aloe"));

But it returns me Boolean values rather than names. How Can I achieve that.

I want to carried out name of elements which contains 'Aloe', such as :

List.of("Tigran Aloe Isolani", "Vassily Aloe Attack", "Vassily New aloe Attack");

But I need to know, if it has with both ['aloe', 'Aloe'], what will be the case?

  • 1
    Use [`filter`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Stream.html#filter(java.util.function.Predicate)) instead of [`anyMatch`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Stream.html#anyMatch(java.util.function.Predicate)) – Florian Cramer Feb 28 '23 at 18:37
  • 1
    Can you update that first snippet to be real code? – Mike 'Pomax' Kamermans Feb 28 '23 at 18:38

1 Answers1

2

First you should use 'filter' and not 'anyMatch'

List<String> aloeLotion = trendyList.stream().filter(str -> str.trim().equals("Aloe"));

Also, You asked for contained 'Aloe' so you should use 'contains' and not 'equals' and also remove the 'trim'

List<String> aloeLotion = trendyList.stream().filter(str -> str.contains("Aloe"));

Finally, since filter is not a stream-terminating function, you should collect the results to list

List<String> aloeLotion = trendyList.stream().filter(str -> str.contains("Aloe")).collect(Collectors.toList());
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
Yogev Caspi
  • 151
  • 12