0

I want to ask about arraylist rearrange

If I have 2 arraylist like this

ArrayList<A> listA;
ArrayList<B> listB;

And if I rearrange listA like this

private static class Descending implements Comparator<A> {
    @Override
    public int compare(A arrayListA, A t1) {
        return t1.getLasttime().compareTo(arrayListA.getLasttime());
    }
}

private void setListTimeSort(ArrayList<A> arrayListA) {
    Descending descending = new Descending();
    Collections.sort(arrayListA, descending);
}

I want to change position together listB.

simple example:

listA before = 1, 2, 3, 4
listB before = a, b, c, d

If listA change = 2, 1, 4, 3, I want to listB change same position item = b, a, d, c.

I changed listA, but I don't know how I can change listB (change position like listA).

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
StarCue
  • 63
  • 9
  • Parallel lists are a bit of an antipattern, and suggest that instead you should use a class (or record) to hold the A and B values, and populate a single list with instances of that class. In this solution there is only one list to sort, and A and B are available together. – Mark Rotteveel Apr 12 '21 at 10:39

1 Answers1

0

This clearly assumes that both lists are the same size.

I would create a new List<Pair<A,B>>, you could then iterate the lists creating a Pair object from items in ListA, and ListB in the same position.

Then sort your list of Pairs (the List<Pair<A,B>>) using a comparator that compares the getKey() part of the pair.

Then iterate the sorted list, creating a List of the getValue() part of the pair.

(I'd probably use streams, but that is the basic idea)

Mike Cargal
  • 6,610
  • 3
  • 21
  • 27
  • maybe your solution will worked for me.. but, can you give me simple example..? i searched about 'pair'. but i can't understand.. :( – StarCue Apr 12 '21 at 02:49
  • i found solution aready. but i don't know where i can share – StarCue Apr 13 '21 at 10:43