Skip to content

Instantly share code, notes, and snippets.

@patricksan
Created August 14, 2019 10:21
Show Gist options
  • Save patricksan/8a5f30aa4cee43c54e0a31287228d82e to your computer and use it in GitHub Desktop.
Save patricksan/8a5f30aa4cee43c54e0a31287228d82e to your computer and use it in GitHub Desktop.
Another option to select the itens that are not duplicated in the stream
package com.moogu.restore;
import java.util.*;
import java.util.stream.Stream;
public class BestApproach {
public static void main(String[] args) {
List<String> letters = Arrays.asList("a", "b", "c", "d", "e", "f", "g", "f", "e", "c", "b");
BestApproach main = new BestApproach();
System.out.println(main.processStream(letters.stream()));
}
private List<String> processStream(Stream<String> stream) {
final Map<String, Integer> content = new HashMap<>();
final List<String> result = new ArrayList<>();
// add content to hash
stream.forEach(x -> addToHash(x, content));
// filter
for (Map.Entry<String, Integer> entry : content.entrySet()) {
if (entry.getValue() == 1) {
result.add(entry.getKey());
}
}
return result;
}
private void addToHash(String x, Map<String, Integer> content) {
if (content.containsKey(x)) {
Integer actualValue = content.get(x);
content.put(x, ++actualValue);
} else {
content.put(x, 1);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment