简体   繁体   English

Java ArrayList以相同顺序对两个列表进行排序

[英]Java ArrayList sort two lists in same order

I have two ArrayLists in Java. 我在Java中有两个ArrayList。 Both lists are unsorted. 这两个列表均未排序。

    ArrayList<Integer> listOne = new ArrayList<>();
    listOne.add(2);
    listOne.add(1);
    listOne.add(4);
    listOne.add(8);
    listOne.add(6);

    ArrayList<String> listTwo = new ArrayList<>();
    listTwo.add("ant");
    listTwo.add("bear");
    listTwo.add("cat");
    listTwo.add("dog");
    listTwo.add("zebra");

I want to sort listOne in natural order and each item of listTwo should be sorted according to the position in listOne: 我想以自然顺序对listOne进行排序,并且listTwo的每个项目都应根据listOne中的位置进行排序:

What I have so far is: 到目前为止,我有:

  Collections.sort(listOne);

  for (int i = 0; i < listOne.size(); i++) {

        int intTest = listOne.get(i);
        String stringTest = listTwo.get(i);

        System.out.println(intTest);
        System.out.println(stringTest);

    }

This prints : 打印:

  1 ant, 2 bear, 4 cat , 6 dog , 8 zebra

My expected print output is: 我预期的打印输出是:

  1 bear, 2 ant, 4 cat, 6 zebra, 8 dog

So that when the item of listOne "1", that changed the position from 2nd to 1st, the item "bear" in listTwo, that was on the 2nd position, should also print on the 1st position. 因此,当listOne的项目“ 1”将位置从第2更改为第1时,listTwo中的项目“ bear”在第2位置也应在第1位置打印。

What would be the most simple and efficient way to do this? 什么是最简单有效的方法?

Create an ordered list of indices: 创建索引的有序列表:

int n = listOne.size();
assert n == listTwo.size();

Integer[] indices = new Integer[n];
for (int i = 0; i < n; ++i) {
  indices[i] = i;
}

Sort that list using a comparator that compares indices by looking at the corresponding elements in listOne. 使用比较器对列表进行排序,该比较器通过查看listOne中的相应元素来比较索引。

Arrays.sort(
    indices,
    new Comparator<Integer>() {
      public int compare(Integer a, Integer b) {
        return listOne.get(a).compareTo(listOne.get(b));
      }
    });

Now you can use indices to reorder both lists: 现在,您可以使用索引对两个列表重新排序:

static <T> void reorder(Integer[] indices, List<T> mutatedInPlace) {
  List<T> tempSpace = new ArrayList<T>(indices.length);
  for (int index : indices) {
    tempSpace.add(mutatedInPlace.get(index);
  }
  mutatedInPlace.clear();
  mutatedInPlace.addAll(tempSpace);
}

reorder(indices, listOne);
reorder(indices, listTwo);

TreeMap best suits this situation. TreeMap最适合这种情况。 It inserts the data in sorted order so basically store the key and against each key you can store the animal. 它按排序顺序插入数据,因此基本上可以存储密钥,并且可以针对每个密钥存储动物。

Map<Integer,String> sortedMap = new TreeMap<Integer,String>();
sortedMap.push(listOne.get(i),listTwo.get(listOne.get(i)));

In case you want to stick to ArrayList, you can iterate over the listOne and push it in HashMap<Integer,String> 如果要坚持使用ArrayList,可以遍历listOne并将其推入HashMap<Integer,String>

iterate over list (for example i)
map.put( listOne.get(i), secondList.get(i));

So the hashMap would be like (2, "ant"); 所以hashMap就像(2, "ant");

  • Collections.sort(listOne); Collections.sort(listOne);
  • Against each entry, you can get the corresponding animal from map 针对每个条目,您可以从地图上获取相应的动物

If you use a Map<Integer, String> for this, you don't even need to sort it if you take the TreeMap implementation. 如果为此使用Map<Integer, String> ,则采用TreeMap实现时甚至不需要对其进行排序。

It basically works as follows: 它的基本工作原理如下:

public class StackoverflowMain {

    public static void main(String[] args) {
        // initialize a map that takes numbers and relates Strings to the numbers
        Map<Integer, String> animals = new TreeMap<Integer, String>();
        // enter ("put" into the map) the values of your choice
        animals.put(2, "ant");
        animals.put(1, "bear");
        animals.put(4, "cat");
        animals.put(8, "dog");
        animals.put(6, "zebra");
        // print the whole map using a Java 8 forEach statement
        animals.forEach((index, name) -> System.out.println(index + ": " + name));
    }

}

This code will output 此代码将输出

1: bear
2: ant
4: cat
6: zebra
8: dog

We can use HashMap data structure, It contains “key-value” pairs and allows retrieving the value by key. 我们可以使用HashMap数据结构,它包含“键-值”对,并允许按键检索值。

 int i = 0; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 

Here we're storing the items from listOne as keys and their position as a value in the HashMap. 在这里,我们将listOne中的项存储为键,并将其位置存储为HashMap中的值。

for (Integer num : listOne) {
        map.put(num, i);
        i++;
    }

We're printing the elements from listTwo as per the items from the listOne changed their position. 我们正在根据listOne中的项目打印listTwo中的元素,以更改其位置。

Collections.sort(listOne);
    for (Integer num : listOne) {
        System.out.println(num + " " + listTwo.get(map.get(num)));
    }

One Solution: 一种解决方案:

    int i = 0;
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (Integer num : listOne) {
        map.put(num, i);
        i++;
    }
    Collections.sort(listOne);
    for (Integer num : listOne) {
        System.out.println(num + " " + listTwo.get(map.get(num)));
    }

Output is: 输出为:

1 bear, 2 ant, 4 cat, 6 zebra, 8 dog 1熊,2蚂蚁,4猫,6斑马,8狗

Putting the suggestions of all the friendly and helpful people together (plus some other research and test), here is the final code I came up with: 将所有友好和乐于助人的人的建议放在一起(加上一些其他研究和测试),这是我想出的最终代码:

ArrayList<String> listOne = new ArrayList<>();
listOne.add("one");
listOne.add("eight");
listOne.add("three");
listOne.add("four");
listOne.add("two");

ArrayList<String> listTwo = new ArrayList<>();
listTwo.add("ant");
listTwo.add("bear");
listTwo.add("cat");
listTwo.add("dog");
listTwo.add("zebra");

Map<String, String> sortedMap = new TreeMap<String, String>();

for (int i = 0; i < listOne.size(); i++) {

    String stringkey = listOne.get(i);
    String stringValue = listTwo.get(i);

    sortedMap.put(stringkey, stringValue);
}

print output = {eight=bear, four=dog, one=ant, three=cat, two=zebra}

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

相关问题 Java按字母顺序对ArrayList进行排序,并对其他数组进行相同的更改 - Java sort ArrayList in alphabetical order and doing the same changes on other arrays 使用Java中具有相同type属性的另一个arraylist的顺序,按对象属性对arraylist进行排序 - Sort an arraylist by an object property using the order of another arraylist with same type property in Java 按两个字段排序Arraylist(Java) - Sort an Arraylist by two fields (Java) 两个或更多列表的公共元素(相同顺序)的Java最小分区 - Java smallest partition of common elements (in the same order) of two or more lists Java 比较两个相同大小的字符串列表,其中顺序很重要 - Java compare two lists of String of same size where order is important 如何按升序对 ArrayList 的元素进行排序? - Java - How to sort elements of ArrayList in ascending order? - Java Java,按自定义alpha顺序排序arraylist - Java, sort arraylist by custom alpha order Java ArrayList - 我如何判断两个列表是否相等,顺序无关紧要? - Java ArrayList - how can I tell if two lists are equal, order not mattering? 比较两个ArrayList <String> Java列表 - Comparting two ArrayList<String> lists in Java 如何按 java 中数值的升序对包含相同大小列表的列表进行排序 - How to sort a List containing lists of the same size in the asscending order of thier numerical value in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM