[java] Getting Index of an item in an arraylist;

I have a Class called AuctionItem. The AuctionItem Class has a method called getName() that returns a String. If I have an ArrayList of type AuctionItem, what is the best way to return the index of an item in the ArrayList that has a specific name?

I know that there is an .indexOf() function. The parameter for this function is an object. To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList?

Is there a better way?

This question is related to java arraylist find element indexof

The answer is


.indexOf() works well. If you want an example here is one:

  ArrayList<String> example = new ArrayList<String>();
  example.add("AB");
  example.add("CD");
  example.add("EF");
  example.add("GH");
  example.add("IJ");
  example.add("KL");
  example.add("MN");

  System.out.println("Index of 'AB': "+example.indexOf("AB"));
  System.out.println("Index of 'KL': "+example.indexOf("KL"));
  System.out.println("Index of 'AA': "+example.indexOf("AA"));
  System.out.println("Index of 'EF': "+example.indexOf("EF"));

will give you an output of

Index of 'AB': 0
Index of 'KL': 5
Index of 'AA': -1
Index of 'EF': 2

Note: This method returns -1 if the specified element is not present in the list.


Basically you need to look up ArrayList element based on name getName. Two approaches to this problem:

1- Don't use ArrayList, Use HashMap<String,AutionItem> where String would be name

2- Use getName to generate index and use index based addition into array list list.add(int index, E element). One way to generate index from name would be to use its hashCode and modulo by ArrayList current size (something similar what is used inside HashMap)


for (int i = 0; i < list.length; i++) {
   if (list.get(i) .getName().equalsIgnoreCase("myName")) {
    System.out.println(i);
    break;
  }
}

To find the item that has a name, should I just use a for loop, and when the item is found, return the element position in the ArrayList?

Yes to the loop (either using indexes or an Iterator). On the return value, either return its index, or the item iteself, depending on your needs. ArrayList doesn't have an indexOf(Object target, Comparator compare)` or similar. Now that Java is getting lambda expressions (in Java 8, ~March 2014), I expect we'll see APIs get methods that accept lambdas for things like this.


Yes.you have to loop it

public int getIndex(String itemName)
{
    for (int i = 0; i < arraylist.size(); i++)
    {
        AuctionItem auction = arraylist.get(i);
        if (itemName.equals(auction.getname()))
        {
            return i;
        }
    } 

    return -1;
}

I think a for-loop should be a valid solution :

    public int getIndexByname(String pName)
    {
        for(AuctionItem _item : *yourArray*)
        {
            if(_item.getName().equals(pName))
                return *yourarray*.indexOf(_item)
        }
        return -1;
    }

Rather than a brute force loop through the list (eg 1 to 10000), rather use an iterative search approach : The List needs to be sorted by the element to be tested.

Start search at the middle element size()/2 eg 5000 if search item greater than element at 5000, then test the element at the midpoint between the upper(10000) and midpoint(5000) - 7500

keep doing this until you reach the match (or use a brute force loop through once you get down to a smaller range (eg 20 items)

You can search a list of 10000 in around 13 to 14 tests, rather than potentially 9999 tests.


You could implement hashCode/equals of your AuctionItem so that two of them are equal if they have the same name. When you do this you can use the methods indexOf and contains of the ArrayList like this: arrayList.indexOf(new AuctionItem("The name")). Or when you assume in the equals method that a String is passed: arrayList.indexOf("The name"). But that's not the best design.

But I would also prefer using a HashMap to map the name to the item.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arraylist

Adding null values to arraylist How to iterate through an ArrayList of Objects of ArrayList of Objects? Dynamically adding elements to ArrayList in Groovy How to replace existing value of ArrayList element in Java How to remove the last element added into the List? How to append elements at the end of ArrayList in Java? Removing Duplicate Values from ArrayList How to declare an ArrayList with values? In Java, can you modify a List while iterating through it? Load arrayList data into JTable

Examples related to find

Find a file by name in Visual Studio Code Explaining the 'find -mtime' command find files by extension, *.html under a folder in nodejs MongoDB Show all contents from all collections How can I find a file/directory that could be anywhere on linux command line? Get all files modified in last 30 days in a directory FileNotFoundError: [Errno 2] No such file or directory Linux find and grep command together find . -type f -exec chmod 644 {} ; Find all stored procedures that reference a specific column in some table

Examples related to element

How can I loop through enum values for display in radio buttons? How to count items in JSON data Access multiple elements of list knowing their index Getting Index of an item in an arraylist; Octave/Matlab: Adding new elements to a vector add item in array list of android GetElementByID - Multiple IDs Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? Check if one list contains element from the other How to get the focused element with jQuery?

Examples related to indexof

Uncaught TypeError: .indexOf is not a function indexOf and lastIndexOf in PHP? Finding second occurrence of a substring in a string in Java Index of element in NumPy array Getting Index of an item in an arraylist; In an array of objects, fastest way to find the index of an object whose attributes match a search Get value of a string after last slash in JavaScript How to find the array index with a value? Where is Java's Array indexOf? How to trim a file extension from a String in JavaScript?