Reputation: 161
I have if condition where I am checking for String equality, if they match I store them in Set. Then I am looping through Set to check if ENUM3
value is present, if yes I replace that particular string with value String Java
. I am using Iterator to loop and check for equality. I am looking for same functionality with use of streams where
1. I can loop through Set
2. Check for String equality
3. If ENUM3 found then replace with Java
4. Save all the matched String
Here is my code
{
Set<String> only = new HashSet<String>();
Iterator<Mark> itr = Marks.iterator();
while (itr.hasNext()) {
Mark find = itr.next();
if (ENUM1.getData().equals(find.search())||ENUM3.getData().equals(find.search())) {
only.add(find.search());
only = only.stream()
.map(macro -> macro.equals(ENUM3.getData()) ? "Java" : macro).collect(Collectors.toSet());
}
}
}
Here is what I tried using Stream
only = only.stream()
.map(macro -> macro.equals(ENUM3.getData()) ? "Java" : macro)
.collect(Collectors.toSet());
Upvotes: 3
Views: 2496
Reputation: 45329
This should perform your entire operation:
Set<String> only = Marks.stream()
.map(Mark::search)
.filter(mark -> ENUM1.getData().equals(mark)
|| ENUM2.getData().equals(mark)
|| ENUM3.getData().equals(mark))
.map(macro -> macro.equals(ENUM3.getData()) ? "Java" : macro)
.collect(Collectors.toSet());
You seem to be unnecessarily doing these 2 (both of which are avoided in the pipeline above)
only
in each iteration to replace ENUM3.getData()
with Java
Mark.search()
Upvotes: 2