简体   繁体   English

如何将arrayList元素转换为2D数组?

[英]How to transfer arrayList elements into a 2D array?

I have an ArrayLists called List<Pair> patternList = new ArrayList<>() that contains a number of patterns of length 2. for example, for A={1,2,3,4} I create some patterns like (1,3)(3,2)...etc. 我有一个ArrayLists称为List<Pair> patternList = new ArrayList<>()包含了许多例如长度为2的图案,A = {1,2,3,4}我创建一些状图案(1, 3)(3,2)...等。 I want to put these patterns into a 2d array(matrix)[A][A] in way that the patterns must go into a specific index in the matrix, For instance pattern (1,3) must go into index [3][3] or pattern (3,2) must go in [2][2]. 我想将这些模式放入二维数组(matrix)[A] [A]中,以便模式必须进入矩阵中的特定索引,例如模式(1,3)必须进入索引[3] [ 3]或模式(3,2)必须进入[2] [2]。

Thanks. 谢谢。

If you just want to put them in by the second index. 如果您只是想将它们放在第二个索引中。 (edited to allow multiple per index): (已编辑,以允许每个索引多个):

List<Pair>[][] matrix = new LinkedList<Pair>[5][5]; //Replace 5 here a getter for the maximum value of A
                                  //Here it's 5 because the max of your example is 4.
//Initialize all positions of matrix to empty list.
for (int r = 0; r < matrix.length; r++){
    for(int c = 0; c < matrix[r].length; c++){
        matrix[r][c] = new LinkedList<Pair>();
    }
}
for (Pair p : patternList){
    if (matrix[p.second][p.second] == null)
        matrix[p.second][p.second] = new LinkedList<Pair>();
    matrix[p.second][p.second].add(p);
}

This isn't really using the 2d aspect of the array though; 但是,这实际上并没有使用数组的2d方面。 you could accomplish exactly the same thing with a 1d array of lists: 您可以使用一维列表数组完成完全相同的操作:

List<Pair>[] arr = new LinkedList<Pair>[5]; //Replace 5 here a getter for the maximum value of A
                                  //Here it's 5 because the max of your example is 4.
//Initialize all positions of array to empty list.
for (int r = 0; r < matrix.length; r++){
    arr[r] = new LinkedList<Pair>();
}
for (Pair p : patternList){
    if (arr[p.second] == null)
        arr[p.second] = new LinkedList<Pair>();
    arr[p.second].add(p);
}

Since you want to keep more than one element at each position, I suggest you use a Multimap . 由于您想在每个位置保留多个元素,因此建议您使用Multimap A Multimap is basically a Map<Key, Collection<Value>> that takes care of creating the collections for you. Multimap是一个Map<Key, Collection<Value>> ,它负责为您创建集合。

Multimap Multimap之

 Multimap<List<Integer>, Pair> myMap = ArrayListMultimap.create();

 for (Pair p : myPairs){
     List<Integer> key = Lists.newArrayList(p.second, p.second);
     myPair.put(key, p);
 }

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

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