Java – How to keep the original order in an ArrayList for unique values

arraylistjavalist

For example if i want to preserve the order of the string that appear first, but I also want the second occurrence of the duplicate to follow after the first one on the list of output. for example if I added:
arrlist.add("bob");
arrlist.add("pat");
arrlist.add("tan");
arrlist.add("bob");
arrlist.add("mat");
arrlist.add("cat");
arrlist.add("dog");
arrlist.add("cat");

I want the output to be

String = bob
String = bob
String = pat
String = tan
String = mat
String = cat
String = cat
String = dog

This is my code:

package com.tutorialspoint;

import java.util.ArrayList;

public class ArrayListDemo {
    public static void main(String[] args) {

        // create an empty array list with an initial capacity
        ArrayList<String> arrlist = new ArrayList<String>();

        // use add() method to add elements in the list
        arrlist.add("bob");
        arrlist.add("pat");
        arrlist.add("tan");
        arrlist.add("bob");
        arrlist.add("mat");
        arrlist.add("cat");
        arrlist.add("dog");
        arrlist.add("cat");

        // let us print all the elements available in list
        for (String number : arrlist) {
            System.out.println("String = " + number);
        } 

        // retrieves element at 4th postion
        String retval=arrlist.get(3);
        System.out.println("Retrieved element is = " + retval); 


    }
} 

Best Answer

You can get the index of a value in the list with indexOf(yourString). You can use that to check if the entry exists and insert the value after that one. See the javadocs for more information.

Something along the lines of

if(arrlist.indexOf(myString) == -1) // Not found
   arrlist.add(myString)
else
   arrlist.add(arrlist.indexOf(myString), myString)

Well there I did it, wrote you the code...shame on me.

Related Topic