Home » Java » Finding index of recurring objects in an ArrayList in Java-Exceptionshub

Finding index of recurring objects in an ArrayList in Java-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:
public class NewMain {
    public static void main(String[] args) {
        ArrayList<String> array = new ArrayList<>();
        array.add("Ace of Hearts");
        array.add("King of Clubs");
        array.add("Three of Spade");
        array.add("Ace of Hearts");
        array.add("Ten of Clubs");
        for(String s: array)
            System.out.println(s+"at postion: "+array.indexOf(s));
    }
}

IndexOf() returns the first occurence of the object in an ArrayList.
Assuming my code is the hand of a poker player, and I want to know the indices of the cards he is holding. Ace of Hearts is at positon 1 and 4. But IndexOf() returns as position 1 and 1 for both occurences of Ace of Hearts.

Question:
1)Is there any other way of getting the value?
2)Should I use someother Data Structure like HashMap or something else?

How to&Answers:

The List.indesOf() method will return the first occurrence of the list. But your requirement can fulfill as following way.

    import java.util.ArrayList;

    public class NewMain {
        public static void main(String[] args) {
            ArrayList<String> array = new ArrayList<>();
            array.add("Ace of Hearts");
            array.add("King of Clubs");
            array.add("Three of Spade");
            array.add("Ace of Hearts");
            array.add("Ten of Clubs");
            for(int i =0;i<array.size();i++)
                System.out.println(array.get(i)+"at postion: "+i);
        }
    }

Answer:

This should solve your problem :

 public class NewMain {
        public static void main(String[] args) {
            String abc="Ace of Hearts";
            List<String> array = new ArrayList<String>();
            array.add("Ace of Hearts");
            array.add("King of Clubs");
            array.add("Three of Spade");
            array.add("Ace of Hearts");
            array.add("Ten of Clubs");
            List<Integer> indexList= indexOfAll(abc,array);
            System.out.println(indexList);

        }

        static <T> List<Integer> indexOfAll(T obj, List<T> list) {
            final List<Integer> indexList = new ArrayList<Integer>();
            for (int i = 0; i < list.size(); i++) {
                if (obj.equals(list.get(i))) {
                    indexList.add(i);
                }
            }
            return indexList;
        }