Home > OS >  Sorting two arraylists in same order
Sorting two arraylists in same order

Time:01-19

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.

CodePudding user response:

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);
        }
    }
}

CodePudding user response:

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]

CodePudding user response:

One possibility would be to group each number (int) with its name (String) in a class (Java < 15) or record (Java >= 15):

record NumberWithName(int value, String name) {
}

Then, for each pair of int and String from the two Lists, construct a Number-instance and add it to a new 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:

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

This produces the following 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]]

CodePudding user response:

To sort the values you can use the special data structure 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());
}

CodePudding user response:

A TreeMap should help here where your key is the integer and the value represents the string. TreeMap is directly sorted by the key.

  •  Tags:  
  • java
  • Related