user3009344 user3009344 - 1 month ago 19
Java Question

Java lambda loop

I am still figuring out lambdas and I am wondering about one method.

private enum Result
{
RESULT1,
RESULT2,
RESULT3
}
public static Map<String, Result> calculateResults(List<String> list)
{
Map<String, Result> map = new HashMap<>(list.size());
List<String> leavings = new ArrayList<>(list);

map.putAll(leavings.stream().filter(Main::firstFilter).collect(Collectors.toMap(s -> s, s -> Result.RESULT1)));
leavings.removeAll(map.keySet());

map.putAll(leavings.stream().filter(Main::secondFilter).collect(Collectors.toMap(s -> s, s -> Result.RESULT2)));
leavings.removeAll(map.keySet());

map.putAll(leavings.stream().filter(Main::thirdFilter).collect(Collectors.toMap(s -> s, s -> Result.RESULT3)));
leavings.removeAll(map.keySet());

return map;
}
private static boolean firstFilter(String s)
{
return s.length() == 5;
}
private static boolean secondFilter(String s)
{
return s.contains("A");
}
private static boolean thirdFilter(String s)
{
return BlockedStrings.getInstance().contains(s);
}


I think it would be super awesome if this could be made in some kind of the loop, but i have got no clue how to code it. Is it possible to assign filter Predicate to the enum variable or do anything else to not make it so repeatable?

Answer

I’m not sure, whether I got your intention right, but to me, it looks like you want to do:

public static Map<String, Result> calculateResults(List<String> list) {
    return list.stream().filter(s -> firstFilter(s)||secondFilter(s)||thirdFilter(s))
        .collect(Collectors.toMap(s -> s, s -> firstFilter(s)? Result.RESULT1:
                              secondFilter(s)? Result.RESULT2: Result.RESULT3));
}

This has the disadvantage of evaluating the predicates multiple times. The alternative is to store the evaluation result into temporary objects:

public static Map<String, Result> calculateResults(List<String> list) {
    return list.stream().map(s -> new AbstractMap.SimpleImmutableEntry<>(s,
            firstFilter(s)? Result.RESULT1: secondFilter(s)? Result.RESULT2:
            thirdFilter(s)? Result.RESULT3: null))
        .filter(e -> e.getValue()!=null)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
Comments