2

I'm trying to do what in C# into Java. In C#:

Array.sort(array1, array2);

Where array1 is key and array2 is value

https://msdn.microsoft.com/en-us/library/85y6y2d3(v=vs.110).aspx

Was wondering if Java has something like that as well built in or we have to do some sort of customization.

ra1ned
  • 337
  • 5
  • 19
Jerry Cheng
  • 45
  • 1
  • 7

3 Answers3

3

Nothing as trivial, but converting to a TreeMap, which is automatically sorted, is likely the best way to go:

Map<String, int> map = new TreeMap<String, int>();

for (var i = 0; i < array1.length; i++)
    map.put(array1[i], array2[i]);

To iterate:

for (Map.Entry<String, int> entry : map.entrySet()) {
    // do stuff
}
Drazen Bjelovuk
  • 5,201
  • 5
  • 37
  • 64
1

If you are using Java 8 you could create a stream of array2 sorted according to array1 as follows:

int[] array3 = IntStream.range(0, array1.length).boxed()
    .sorted(Comparator.comparingInt(i -> array1[i]))
    .mapToInt(i -> array2[i])
    .toArray();

Hopefully you can see how that works: it produces a stream of indices, sorts them according to the values in the first array, maps them to the values in the second array and then converts back to an array. Having to box and unbox is only to allow the custom sort (which IntStream doesn't support for some reason).

Here's some sample code to demonstrate:

    int[] array1 = { 5, 4, 3, 2, 1 };
    int[] array2 = { 10, 20, 30, 40, 50 };
    System.out.println(Arrays.toString(IntStream.range(0, array1.length).boxed()
            .sorted(Comparator.comparingInt(i -> array1[i]))
            .mapToInt(i -> array2[i]).toArray()));

This is assuming the type is int[] but it's easily convertible to any other types. The same approach works for indexible collections.

If the array is of objects then you can use Arrays.sort(T[], Comparator) to sort in place. Java doesn't provide an equivalent for primitive types unfortunately - the assumption is that you want to sort by their natural order.

sprinter
  • 27,148
  • 6
  • 47
  • 78
  • I can't compile using this code: array2 must be final to be used on `.mapToInt`; after making thins change, I got wrong index... maybe I did something wrong, could you, please, take a second look on this code? – Gerardo Lima May 28 '18 at 16:21
  • 1
    You need to assign to a new array variable. Will update my solution. – sprinter May 28 '18 at 22:19
0

I'm not aware of any such util in the JDK. Here is how you can implement it:

import java.util.Arrays;

class Sort {
  public static <K extends Comparable<K>,V> void sort(K[] k, V[]v) {
    class Kv implements Comparable<Kv> {
       K k;
       V v;
       public Kv(K k, V v) {
         this.k = k;
         this.v = v;
       }
       public int compareTo(Kv other) {
         return k.compareTo(other.k);
       }
    }
    if (k.length != v.length) {
       throw new Error("not same length");
    }
    Kv[] kv = new Kv[k.length];
    for (int i=0; i<k.length; i++) {
      kv[i] = new Kv(k[i], v[i]);
    }
    Arrays.sort(kv);
    for (int i=0; i<k.length; i++) {
      k[i] = kv[i].k;
      v[i] = kv[i].v;
    }
  }

  public static void main(String[] args) {
    Character[] v = {'a', 'b', 'c'};
    Integer[] k1 = {5, 3, 2};

    Sort.sort(k1, v);
    for(int i=0; i<k1.length; i++) {
      System.out.println(v[i]);
    }
  }
}
Roberto Attias
  • 1,883
  • 1
  • 11
  • 21