How to move specific item in array list to the first item in Java?


To move an item from an ArrayList and add it to the first position you need to -

  • Get the position (index) of the item using the indexOf() method of the ArrayList class.
  • Remove it using the remove() method of the ArrayList class.
  • Finally, add it to the index 0 using the add() method of the ArrayList class.

Example

Live Demo

import java.util.ArrayList;

public class ArrayListSample {
   public static void main(String args[]) {
      ArrayList al = new ArrayList();
      al.add("JavaFX");
      al.add("HBase");
      al.add("WebGL");
      al.add("OpenCV");
      System.out.println(al);
      String item = "WebGL";
      int itemPos = al.indexOf(item);
      al.remove(itemPos);
      al.add(0, item );
      System.out.println(al);
   }
}

Output

[JavaFX, HBase, WebGL, OpenCV]
[WebGL, JavaFX, HBase, OpenCV]

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 19-Dec-2019

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements