0

I have a custom ArrayList. I need to re-arrange this ArrayList in particular order with respect to an integer Array. E.g

List<String> test = new ArrayList();        
    test.add("red");
    test.add("green");
    test.add("blue");
int [] X = {2,0,1};

Re-arrange this arrayList w.r.t X array. i.e item at 2nd index should come to 1st, 0th item to 2nd position and 1st item to 3rd position

Output should be:

blue
red
green

I know how to do it using for loop just want to know if there is any better solution then this.

Nishant Tanwar
  • 383
  • 4
  • 8
  • 18
  • 2
    How about creating a Class that has `ID` and `color` as fields. And then making of `ArrayList` of that class and then sort them with custom comparator based on `ID` ? – Anand Undavia Mar 03 '17 at 09:17
  • Other than creating a new wrapper class which can be sorted by ID, I don't see a clean way of doing this. – Tim Biegeleisen Mar 03 '17 at 09:17
  • Actually it's not a duplicate of that question, in this case is needed to move elements in custom order, not rotating the position – RudiDudi Mar 03 '17 at 09:24
  • you may try this by adding elements with indexes from the primitive array to a new array: `int i=0; List res = new ArrayList(); while(i – Sumit Sagar Mar 03 '17 at 09:25
  • for(int i=0;i – rathna Mar 03 '17 at 09:39

2 Answers2

0

You can create a Map and map the integer to the String Value.

Iterate the reference array and get it listed based on your order.

Snippet:

Map<Integer,String> maps = new HashMap<Integer,String>();
maps.put(1,"Red");
maps.put(2,"White");

for(Integer a : values){
   System.out.println(maps.get(a));
}
sitakant
  • 1,766
  • 2
  • 18
  • 38
  • A TreeMap would be better suited – Maurice Perry Mar 03 '17 at 09:25
  • Not required . We are not going for sorting mechanism in this approach... We are mapping value and we'll display the value based on the array order. Introducing TreeMap will have some more complexity while adding the value as compared to HashMap... – sitakant Mar 03 '17 at 09:35
  • But the Input is a list not a map and the Output should also be a list and not text in the console. So your solution does not fit the requirements – Jens Mar 03 '17 at 09:50
  • I dont think , It is complex to create a list if we have appropriate values with us. – sitakant Mar 03 '17 at 09:51
-1

You can use

Collections.swap(test,1,2);
Collections.swap(test,2,3);

Documentation Here

RudiDudi
  • 455
  • 1
  • 7
  • 18