根据多个“可选"条件过滤HashMap [英] Filter HashMap based on multiple 'optional' conditions

查看:117
本文介绍了根据多个“可选"条件过滤HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个需要在函数中过滤的HashMap:

I have a HashMap that I need to filter in a function:

public void filter(filterOption1, filterOption2, filterOption3, filterOption4) {
    //Filter map in here
    ...
} 

过滤器选项 filterOption1 filterOption2 filterOption3 filterOption4 在运行时可能为null,我想要避免的事情是这样的:

The filter options filterOption1,filterOption2,filterOption3,filterOption4 might be null during runtime, and what I'm looking to avoid is something in the likes of:

public void filter(filterOption1, filterOption2, filterOption3, filterOption4) {
    if(filterOption1 != null && filterOption2 == null && filterOption3 == null && filterOption4 == null) {
        // Filter map values on filterOption1
    } else if(filterOption1 != null && filterOption2 != null && filterOption3 == null && filterOption4 == null) {
        // Filter map values on filterOption1 and filterOption2
    } else if ... // And so on
    
} 

是否有某种方法可以避免通过 map.stream()的一些巧妙过滤来链接16条if语句?

Is there some way of avoiding chaining 16 if-statements through some clever filtering with map.stream()?

推荐答案

这里是一种解决方案.它说明您不需要一系列if语句.

Here's one solution. It illustrates that you don't need a sequence of if statements.

您可以通过向过滤器传递谓词集合来进一步改善情况.

You could improve things further by passing filter a collection of Predicates.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

public class FilterOption {
    public static void main(String... args) {
        FilterOption f = new FilterOption();

        System.out.println(f.theMap);
        f.filter(null, null);
        System.out.println(f.theMap);
        f = new FilterOption();
        f.filter(null, s -> s.startsWith("f"));
        System.out.println(f.theMap);
    }

    public FilterOption() {
        theMap.put("a", "foo");
        theMap.put("b", "bar");
    }

    Map<String, String> theMap = new HashMap<>();

    // assume we are filtering the values of the map
    // and assume that we keep the key if no filter
    // is false, and that a missing filter is true
    public void filter(Predicate<String> filterOption1,
                       Predicate<String> filterOption2) {
        List<Map.Entry<String, String>> entries =
                new ArrayList(theMap.entrySet());
        for (Map.Entry<String, String> entry : entries) {
            if (!keep(entry.getValue(), filterOption1)
                    || !keep(entry.getValue(), filterOption2)) {
                theMap.remove(entry.getKey());
            }
        }
    }

    private boolean keep(String value, Predicate<String> filterOption) {
        return filterOption == null || filterOption.test(value);
    }
}

这篇关于根据多个“可选"条件过滤HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆