-1

I know how I can replace Items using Collections class but I wanna move Item but not replace any Items

List<String> list = new ArrayList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        /*
        Outputs
        {A,B,C,D}
        I wanna move C to 0 on list and move A to 1 on list like this
        {C,A,B,D}
        */

in fact I have comments List and I wanna show user comments first in recyclerview like Youtube.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Taha Sami
  • 1,565
  • 1
  • 16
  • 43

2 Answers2

0

It is better to use LinkedList instead of ArrayList because of fast timing for add and remove process, so you can do this :

List<String> list = new LinkedList<>();
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");

String element = list.get(2); 
list.remove(2); 
list.addFirst(element);

and also if it not depends on the index and the value is matter below code maybe helpful :

Iterator it = list.iterator();
while (it.hasNext()) {
    Object thing = it.next();
    if (ThisIsTheObjectWeAreLookingFor(thing)) {
        it.remove();
        list.addFirst(thing);
        return thing;
    }
}
0

Same question was asked and answered before: Moving items around in an ArrayList

For your example:

Collections.rotate(list.subList(0, 3), 1);

There are other possibilities like this:

list.add(0, list.remove(2));
anonymus1994.1
  • 308
  • 1
  • 6