简体   繁体   English

如何使用 map 和 match 执行我的部分代码?

[英]How can I perform my part of code using map and match?

I want to perform this part of my code because previously I had 3 IF for corresponding Match like我想执行这部分代码,因为以前我有 3 个 IF 用于相应的匹配,例如

    if (matcher1.find()) {
        myMap.put(matcher1.group(1), matcher1.group(2)
    }
    if (matcher2.find()) {
        myMap.put(matcher2.group(1), matcher2.group(2)
    }
    if (matcher3.find()) {
        myMap.put(matcher3.group(1), matcher3.group(2)
    }

and I want to know if I can englobe this 3 match in one if and put on my map with the corresponding matcher :) like :我想知道我是否可以将这 3 场比赛合二为一,并将其​​与相应的匹配器放在我的地图上:) 像:

for (int i = 0; i < result.size(); i++) {
            Matcher matcher1= patternRecordType.matcher(result.get(i));
            Matcher matcher2 = patternCustomerAreaRecordType.matcher(result.get(i));
            Matcher match3 = patternTotal.matcher(result.get(i));

            if (matcher1.find() || matcher2.find() || matcher3.find()) {
                myMap.put(matcherX.group(1), matcherX.group(2));
            }

        }

It is not possible to replace your 3 "ifs" with a single one.不可能用一个来替换您的 3 个“如果”。 Note that in the first case, in a single interation you can enter into 3,2,1 or 0 "if" blocks resulting in having 0-3 elements added to the map.请注意,在第一种情况下,在单个交互中,您可以输入 3,2,1 或 0 个“if”块,从而将 0-3 个元素添加到地图中。 If you merge all 3 conditions into a single "if" you will enter the "if" only one at best, resulting at at most 1 added element into the map.如果您将所有 3 个条件合并为一个“if”,您最多只能输入“if”一个,从而导致地图中最多添加 1 个元素。

However, you could create a collection of all the Matchers and then perform matching and adding for each of them.但是,您可以创建所有匹配器的集合,然后为每个匹配器执行匹配和添加。 It would look something like this:它看起来像这样:

List<Matcher> matchers = new ArrayList<>();
Matcher matcher1= patternRecordType.matcher(result.get(i));
Matcher matcher2 = patternCustomerAreaRecordType.matcher(result.get(i));
Matcher matcher3 = patternTotal.matcher(result.get(i));
matchers.add(matcher1);
matchers.add(matcher2);
matchers.add(matcher3);

for (Matcher matcher : matchers){
    if (matcher.find()) {
        myMap.put(matcher.group(1), matcher.group(2));
    }
}

For only 3 Matchers it would be overcomplicating the code but if you have over 5 different Matchers then I would consider something like this.对于只有 3 个匹配器,它会使代码过于复杂,但是如果您有超过 5 个不同的匹配器,那么我会考虑这样的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM