I have this input:
Set<List<String>> allSafe = new HashSet<>(); Set<List<String>> allErrors = new HashSet<>();
How can i filter elements of allErrors based on allSafe? for example if I had:
allErrors = [["h","k"],["hi","ho","ha"]] allSafe = [["h","k"],["sh","ho","ii","oo"],["h","zzz"]]
then the expected output should be:
filteredAllSafe = [["sh","ii","oo"],["zzz"]]
This is my try but it did not work as expected: It returns empty set of list:
public static Set<List<String>> filterSafe(
Set<List<String>> allSafe,
Set<List<String>> allErrors) {
Set<List<String>> filteredSet = allSafe.stream()
.filter(s -> s.contains(allErrors))
.collect(Collectors.toSet());
return filteredSet;
}
Advertisement
Answer
Do it as follows:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Set<List<String>> allErrors = Set.of(
List.of("h", "k"),
List.of("hi", "ho", "ha"));
Set<List<String>> allSafe = Set.of(
List.of("h", "k"),
List.of("sh", "ho", "ii", "oo"),
List.of("h", "zzz"));
Set<List<String>> filteredSet = new HashSet<List<String>>();
boolean found;
List<String> list;
for (List<String> safe : allSafe) {
list = new ArrayList<String>();
for (String strSafe : safe) {
found = false;
for (List<String> error : allErrors) {
for (String strError : error) {
if (strSafe.equals(strError)) {
found = true;
break;
}
}
if (found) {
break;
}
}
if (!found) {
list.add(strSafe);
}
}
if (!list.isEmpty()) {
filteredSet.add(list);
}
}
System.out.println(filteredSet);
}
}
Output:
[[sh, ii, oo], [zzz]]