简体   繁体   English

按相同顺序对两个数组列表进行排序

[英]Sorting two arraylists in same order

I have got two arraylists:我有两个数组列表:

ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(0);
numbers.add(0);
numbers.add(8);
ArrayList<String> linkers = new ArrayList<>();
linkers.add("five");
linkers.add("two");
linkers.add("zero");
linkers.add("zero");
linkers.add("eight");

I need to sort the numbers list in ascending order and get the linkers list sorted in the same order.我需要按升序对数字列表进行排序,并以相同的顺序对链接器列表进行排序。

One possibility would be to group each number ( int ) with its name ( String ) in a class (Java < 15) or record (Java >= 15):一种可能性是将每个数字 ( int ) 与其名称 ( String ) 分组在 class (Java < 15) 或记录 (Java >= 15) 中:

record NumberWithName(int value, String name) {
}

Then, for each pair of int and String from the two List s, construct a Number -instance and add it to a new List numbersWithName :然后,对于来自两个List的每一对intString ,构建一个Number实例并将其添加到一个新的List numbersWithName

List<Integer> values = List.of(5, 2, 0, 0, 8);
List<String> names = List.of("five", "two", "zero", "zero", "eight");
List<NumberWithName> numbersWithName = new ArrayList<>();
for (int index = 0; index < values.size(); ++index) {
  numbersWithName.add(new NumberWithName(values.get(index), names.get(index)));
}

Finally, we sort this List with a corresponding Comparator and print the result:最后,我们用相应的Comparator对这个List进行排序并打印结果:

numbersWithName.sort(Comparator.comparing(NumberWithName::value));
System.out.println(numbersWithName);

This produces the following output:这会产生以下 output:

[NumberWithName[value=0, name=zero], NumberWithName[value=0, name=zero], NumberWithName[value=2, name=two], NumberWithName[value=5, name=five], NumberWithName[value=8, name=eight]]

Parallel lists/arrays are trouble.并行列表/数组很麻烦。 Put corresponding elements into combined objects, then sort those.将相应的元素放入组合对象中,然后对它们进行排序。

import java.util.ArrayList;
import java.util.Comparator;

class Pair {
    public int i;
    public String s;

    public Pair(int _i, String _s) {
        i = _i;
        s = _s;
    }
}

class Test {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(5);
        numbers.add(2);
        numbers.add(0);
        numbers.add(0);
        numbers.add(8);
        ArrayList<String> linkers = new ArrayList<>();
        linkers.add("five");
        linkers.add("two");
        linkers.add("zero");
        linkers.add("zero");
        linkers.add("eight");
        
        ArrayList<Pair> pairs = new ArrayList<>();
        
        for (int i = 0; i < 5; i++) {
            pairs.add(new Pair(numbers.get(i), linkers.get(i)));
        }
        
        pairs.sort(new Comparator<Pair>() { 
            public int compare(Pair a, Pair b) { 
                if (a.i == b.i) return 0;
                else if (a.i < b.i) return -1;
                else return 1;
            }
        });
        
        for (int i = 0; i < 5; i++) {
            System.out.println(pairs.get(i).s);
        }
    }
}

Assuming there is a one-to-one mapping of the number to their name you can do it like so.假设数字与他们的名字是一对一的映射,你可以这样做。 Just sort the indices based on the list of numeric numbers.只需根据数字列表对索引进行排序。 Then use those indices to get each list's values in the proper, sorted order.然后使用这些索引以正确的排序顺序获取每个列表的值。 Here, I just print them to show the results.在这里,我只是打印它们以显示结果。

 List<Integer> indices = IntStream.range(0, numbers.size()).boxed()
         .sorted(Comparator.comparing(numbers::get)).toList();
 
 for (int i : indices) {
     System.out.println(numbers.get(i) + " " + linkers.get(i));
 }

prints印刷

0 zero
0 zero
2 two
5 five
8 eight

They could be "sorted" as follows:它们可以按如下方式“排序”:

numbers = indices.stream().map(numbers::get).toList();
linkers = indices.stream().map(linkers::get).toList();
System.out.println(numbers);
System.out.println(linkers);

prints印刷

[0, 0, 2, 5, 8]
[zero, zero, two, five, eight]

To sort the values you can use the special data structure TreeMap .要对值进行排序,您可以使用特殊的数据结构TreeMap

public static void main(String... args) {
    List<Integer> numbers = List.of(5, 2, 0, 0, 8);
    List<String> linkers = List.of("five", "two", "zero", "zero", "eight");
    List<String> sortedLinkers = sortLinkers(numbers, linkers);
}

public static List<String> sortLinkers(List<Integer> numbers, List<String> linkers) {
    Map<Integer, String> map = new TreeMap<>();
    Iterator<Integer> it1 = numbers.iterator();
    Iterator<String> it2 = linkers.iterator();

    while (it1.hasNext() && it2.hasNext()) {
        map.put(it1.next(), it2.next());
    }

    return new ArrayList<>(map.values());
}

A TreeMap should help here where your key is the integer and the value represents the string. TreeMap 应该在这里提供帮助,其中您的键是 integer,值代表字符串。 TreeMap is directly sorted by the key. TreeMap直接按key排序。

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

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