How do I sort values ​​in multiple lists of arrays?

I have an Arraylist of letters containing a letter f

r

t

d

as well as two

more Arraylists, one of which stores row poistion

letters and the other stores col position

per letter. But after sorting the letters of the Arraylist alphabetically ( Collections.sort(letters)

), how can I sort the row and column values ​​for each letter accordingly? For example, if a letter d

has row = 4

and col ==3

, then after sorting it d

will be in the first place and takes values row

and `` col << 20>. How to do it if letters get values row

and col

.

Given:

ArrayList<Character> letters;
ArrayList<Integer> rows;
ArrayList<Integer> cols;

      

Excerpt:

Collections.sort(letters);
for(int i = 0; i < letters.size(); i++)
{
   System.out.println(letters.get(i).getChar() + rows.get(i) + col.get(i)
}

      

+3


source to share


2 answers


The answer is not to sort the individual arrays, each holding one element of each character.

Create your own class to store three related data attributes eg. Letter

...



Perform one of the following actions:

  • Inject the class Comparable<Letter>

    by adding a method compareTo

    . Then enter ArrayList

    of Letter

    , which you can call Collections.sort

    .
  • Create another class that implements Comparator<Letter>

    with a method compare

    . Use ArrayList

    Letter

    s to call Collections.sort

    , passing in an additional parameter that is an instance of yours Comparator

    .
+5


source


IMHO it couldn't be done out of the box, you can achieve it in two ways:



  • Using any suitable sorting technique (Bubble, Merge, Quick, etc.), sort them manually. Process all three commands, stop when you get letters

    in the order you want.

  • Create a map, key will be your letter, value will be String (rowNum_colNum or use any separator between them) and sort this map by keys. Later, split the value and get both numbers.

0


source







All Articles