3

I have three array lists with String .I want to sort one arraylist and with same order want to set the element of other two list in java. i can sort one list but how to set element of other two list with sorted list order.

Thanks and regards Rahul

sch
  • 27,436
  • 3
  • 68
  • 83
Rahul
  • 344
  • 1
  • 4
  • 16

7 Answers7

8

By far the best way to do this would be to rethink the design and put all three pieces of related data into instances of class designed for this purpose, then just sort the one ArrayList.

Any other method would involve either setting up some Maps to hold the relationships between the Strings, and then manually moving the lists around after sorting the first one (a difficult mess) or writing your own sorting algorithm which moved the second two lists in tandem with the first (probably easier, but an even worse mess.)

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
  • +1 Great answer. The unified data structure could be later split into three different ArrayLists anyway. – Adam Matan Feb 22 '12 at 14:46
  • Thanks for help Ernest. But Actually i dont have any static values. Array list maybe more than three. i mean to say all data are dyanamic.hence i cant create any constant object. then how will do this in above format. – Rahul Feb 23 '12 at 07:16
  • @Rahul -- the only way, then, would be to write your own `sort()` routine which does all the compare operations on one special `ArrayList`, but does the swaps on all of the `ArrayList`s. You could start with the JDK source code for `Collections.sort()` and go from there. – Ernest Friedman-Hill Feb 24 '12 at 14:42
1
private void sortingMechanism() {
for(int i=0;i<list1.size();i++){
    for(int j=i+1;j<list1.size();j++){
        if(list1.get(i)>list1.get(j)){
            Collections.swap(list1, i, j);
            Collections.swap(list2, i, j);
            Collections.swap(list3, i, j);

        }
    }
}
}
Karthik
  • 11
  • 1
0

This is a common need. One option (and you get to use Java's sort, which is probably better than the one you'll write):

/**
 * Sorts by the first list 
 */
static void sort(List... lists) {
    assert lists.length > 0;

    Object[][] objects = new Object[lists[0].size()][lists.length];

    for (int i = 0; i < lists.length; i++) {
        int j = 0;
        for (Object object : lists[i]) {
            objects[j++][i] = object;
        }
    }

    Arrays.sort(objects, new Comparator<Object[]>() {
        public int compare(Object[] o1, Object[] o2) {
            return ((Comparable)o1[0]).compareTo(o2[0]);
        }
    });

    for (int i = 0; i < lists.length; i++) {
        lists[i].clear();
        for (Object[] tuple : objects) {
            lists[i].add(tuple[i]);
        }
    }
}

Use it like

List<String> a = new ArrayList<String>(Arrays.asList(new String[]{"dog", "cat", "cat"}));
List<Integer> b = new LinkedList<Integer>(Arrays.asList(new Integer[]{1, 2, 3}));
List<Object> c = new Vector<Object>(Arrays.asList(new Object[]{"object", 0.5, new Object()}));

sort(a, b, c);

System.out.println(a);
System.out.println(b);
System.out.println(c);

One disadvantage to using this is that it depends on .clear() which is not implemented for some lists, but you could adapt it in that case.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285
0

You can also use hashmap to associate the values of the array that is going to be sorted and the values of the other. After sorting, you can easily find the values of the second array using the first array's values as keys.

Bach
  • 45
  • 1
  • 6
0

One way to do this is to first capture the sorting order then apply it to each individual data list. Here is an example that sorts two arrays without creating specifically designed objects to hold the data from each array or implementing your own sorting algorithm. In addition to the requirements of sorting, its time complexity is O(N) and requires two additional integer arrays of length N. N being the number of elements in each of your data arrays.

public static void main(String[] args) {
  //  Original data in multiple arrays
  String[] letters = new String[] {"C","D","B","E","A"};
  int[] numbers = new int[] {3,4,2,5,1};

  //  Array to hold the destination locations.
  //    Each element refers to the index of the element in the letters array
  //        that goes into that location.
  //    e.g.
  //    The case of [C, D, B, E, A], this array would contain [4, 2, 0, 1, 3].
  //    The 0-th element, 4, means that the 4th element in the source array (A)
  //    should end up in index 0.
  Integer[] srcIndexes = new Integer[letters.length];

  //  Assign indexes
  for (int i = 0; i < letters.length; ++i)
    srcIndexes[i] = i;

  //  Sort the destination index array according to the letters array.
  Arrays.sort(srcIndexes, (Integer a, Integer b) -> letters[a].compareTo(letters[b]));

  //  Array to hold the source locations.
  //    Each element refers to the index where the element in the letters array should go to.
  //    e.g.
  //    The case of [C, D, B, E, A], this array would contain [2, 3, 1, 4, 0].
  //    The 0-th element, 2, means that C should end up in index 2 of the resultant
  //    array (i.e. the destination index).
  int[] dstIndexes = new int[letters.length];
  for (int i = 0; i < letters.length; ++i) {
    dstIndexes[srcIndexes[i]] = i;
  }

  //  Iterate through the indexes to move the data in the data array into their resultant locations.
  for (int srcIndex = 0; srcIndex < letters.length; ) {
    int dstIndex = dstIndexes[srcIndex];

    //  Index is already in place.
    if (srcIndex==dstIndex) {
      ++srcIndex;
      continue;
    }

    //  Swap elements in the source and destination indexes.
    swap(dstIndexes, srcIndex, dstIndex); // Make sure to swap the indexes too.
    swap(letters, srcIndex, dstIndex);  // Swap elements in the letters array.
    swap(numbers, srcIndex, dstIndex);  // Swap elements in the numbers array.
  }

  System.out.println("Indexes : "+Arrays.toString(dstIndexes));
  System.out.println("Letters : "+Arrays.toString(letters));
  System.out.println("Numbers : "+Arrays.toString(numbers));
}

private static <T> void swap(T[] objArray, int i, int j) {
  T tmp = objArray[i];
  objArray[i] = objArray[j];
  objArray[j] = tmp;
}

private static void swap(int[] intArray, int i, int j) {
  int tmp = intArray[i];
  intArray[i] = intArray[j];
  intArray[j] = tmp;
}
Umran
  • 231
  • 2
  • 4
0

If you wrote the sorting code yourself, just expand the part of the code that modifies you first array to modify the other two arrays in the same fashion.

Though the optimal way is to refactor your code to make one list with objects in them that contain the information of all three arrays.

Just as Ernest says :)

oddstar
  • 502
  • 3
  • 12
0

When you sort the first array list instead of only interchanging the elements in the first array list do it also for the other too, using the same index.

arraylist1[x]=arraylist1[y];
arraylist2[x]=arraylist2[y];
arraylist3[x]=arraylist3[y];

Of course there are additional steps when interchanging (like assigning to the auxiliary variable) but that's not what I wanted to show here.

Andrei G
  • 1,590
  • 8
  • 13