检查多维数组是否有来自数组列表的值



假设我的数组列表是:

["b1, "b2", "b3"]

我的多维数组是:

[["b", "b2", "b3"], ["b4", "b5", "b6"], ["b7", "b8", "b9"], ["b", "b4", "b7"], ["b2", "b5", "b8"], ["b3", "b6", "b9"], ["b", "b5", "b9"], ["b3", "b5", "b7"]];

我想检查数组列表中的三个值是否也在多维数组中。

现在的问题是顺序并不重要。为了避免进一步复杂化,您可以简单地"排序"给定数组(我们称其为wordsArray2D)以及列表(我们称其为wordsList)中的每一行。下面是一个示例实现:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
    public static void main(String... args) {
        // This is our "dictionary" of given "lines".
        String[][] wordsArray2D = {{"b1", "b2", "b3"},
                                  {"b4", "b5", "b6"},
                                  {"b7", "b8", "b9"},
                                  {"b", "b4", "b7"},
                                  {"b2", "b5", "b8"},
                                  {"b3", "b6", "b9"},
                                  {"b", "b5", "b9"},
                                  {"b3", "b5", "b7"}};
        // To neglect order, sort each line (since String is Comparable,
        // let's do Array.sort(...) the work for us)
        for (int idx = 0; idx < wordsArray2D.length; ++idx) {
            Arrays.sort(wordsArray2D[idx]);
        }
        // Our input, as List<String>. Add some content
        List<String> wordsList = new ArrayList<String>();
        wordsList.add("b2");
        wordsList.add("b1");
        wordsList.add("b3");
        // To start form even ground, convert the List into an Object[]...
        Object[] wordsListAsArray = wordsList.toArray();
        // ... and sort it as well. Again - this gets rid of ordering problems.
        Arrays.sort(wordsListAsArray);
        for (String[] wordsArray : wordsArray2D) {
            // Tow String[] are equal, iff their Strings at the correspinding
            // indices are equal. For this, we can use Arrays.equals(...)
            if (Arrays.equals(wordsArray, wordsListAsArray)) {
                System.out.println("found.");
                break;
            }
        }
    }
}

使用Collections.sort(Some collection)对多维数组中的每个列表进行排序。稍后使用equals()

检查两个列表是否相同。
    ArrayList all=new ArrayList();
    ArrayList<String> al=new ArrayList<String>();
    al.add("a");
    al.add("b");
    al.add("c");
    ArrayList<String> al1=new ArrayList<String>();
    al1.add("c");
    al1.add("b");
    al1.add("a");
    ArrayList<String> al2=new ArrayList<String>();
    al2.add("a");
    al2.add("c");
    al2.add("b");
    ArrayList<String> al3=new ArrayList<String>();
    al3.add("a");
    al3.add("b");
    al3.add("c");
    all.add(al1);all.add(al2);all.add(al3);
    for(int i=0;i<all.size();i++)
    {
        ArrayList tmp=(ArrayList)all.get(i);
        Collections.sort(tmp);
        if(tmp.equals(al))
        System.out.println(all.get(i));
        //if both are same then do some action here.
    }
输出:

[a, b, c]
[a, b, c]
[a, b, c]

相关内容

  • 没有找到相关文章

最新更新