【问题标题】:cross checking two ArrayList to find a text that contains some words交叉检查两个 ArrayList 以查找包含一些单词的文本
【发布时间】:2020-05-12 10:55:18
【问题描述】:

这里我有两个数组对象,但每个都包含不同类型的对象。 children 包含一个 State 对象//看起来像这样 Nh3 Kf6 20. Ng1 Kg6 21. Nh3 Kf5 22. Rb1 enemyLocation 是一个String name 和String position 的对象,// name 无关紧要,location 看起来像这样 //f5,可以是字母/数字的任意组合。

我需要检查孩子身上是否有任何敌人。位置

例如:

child = Nh3 Kf6 20. Ng1 Kg6 21. Nh3 Kf5 22. Rb1
enemy.position = f5

这返回 null,但是我希望它返回 true,因为 child 在 Kf5 中包含 f5。我知道这是不同的,但如果找到这种组合,我想返回 true。区分大小写。

for (State child: children) {
    for (Enemy enemy: enemyLocation) {
        System.out.println("children: " + child.toString()); // Nh3 Kf6 20. Ng1 Kg6 21. Nh3 Kf5 22. Rb1
        System.out.println("enemyLocation: " + enemy.position.toString()); // f5

        if (child.toString().contains(enemy.position.toString())) {

            target = child;

        }
    }
}

我面临的另一个问题是嵌套循环,我不确定我该如何乐观;我想用 如下所示,但这只会返回真/假,而不会告诉我哪个孩子是那个=敌人

if (children.toString().contains(enemy.toString()))

【问题讨论】:

    标签: java parsing arraylist


    【解决方案1】:

    你能检查一下吗,它可能对你有用。

    public static void main(String[] args) {
            ArrayList<String> list = new ArrayList<>();
            list.add("Nh3 Kf6 20");
            list.add("Ng1 Kg6 21");
            list.add("Nh3 Kf5 22");
            list.add("Rb1");
            String enemy = "f5";
         int index = list.parallelStream().filter(x -> x.indexOf(enemy) > 0).mapToInt(x -> x.indexOf(enemy)).max().orElse(0);// You can directly get index using this function, It will return 0 if there is not any matches found else will return last index(As we have used max)
    
    
    
        }
    

    【讨论】:

    • 我试试看,你能解释一下这行吗``` if (list.parallelStream().filter(x -> x.indexOf(enemy) > 0).collect(Collectors .toList()).size() > 0) { ``` 还有如何找到匹配子节点的索引?
    • 这是一个 Java 8 函数,它将在内部流式传输列表。要获取索引,您可以使用 System.out.println(list.parallelStream().filter(x -> x.indexOf(enemy) > 0).map(x -> x.indexOf(enemy)).collect(Collectors .toList()));这将提供索引列表。
    • 这会给你索引 int direclty.int index = list.parallelStream().filter(x -> x.indexOf(enemy) > 0).mapToInt(x -> x.indexOf(敌人)).max().orElse(0);
    • 如果您遇到任何问题或困惑,请告诉我
    【解决方案2】:

    假设敌方位置不同,可以使用String类内置的indexOf方法获取与之匹配的child。

    if(children.toString().contains(enemy.toString())){
        String[] temp = Arrays.toString(children).split("[^a-zA-Z0-9']\\s");
        int index = Arrays.asList(temp).indexOf(enemy.toString());
        target = children[index - 1]; //the -1 is due to brackets being part of 
        //string 
        //or children.get(index) depending on what type of array object you're 
        //using
    }
    

    【讨论】:

    • 我试了一下,效果如何,但由于我一开始所说的问题,我不确定这是否可行。
    • 注意到提供的代码中有一个小错误。这是新的。
    猜你喜欢
    • 2014-07-17
    • 2014-02-10
    • 2019-07-15
    • 1970-01-01
    • 2022-01-15
    • 2012-11-21
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多