is there a way with the index of function to return the index of a value that is part of a class like just one field of the bigger structure.. I got a simple contact class and I want to return the index when the id is a certain value .. should I be using a different structure than an arrayList it is doing most of what I want but the index of function is frustrating
-
2`for(int i=0;i
– Eugene May 17 '21 at 21:15 -
Maybe you could use a Map rather than a list. – NomadMaker May 17 '21 at 21:39
4 Answers
I think the easiest way is to just iterate over the array, and check the condition with "if". That will be O(n).

- 21
- 3
You can use the Predicate method explained here.
Optional<Integer> indexOfMatch = IntStream.range(0, yourList.size())
.filter(i -> valueYouAreLookingFor.equals(yourList.get(i).getFieldYouAreChecking()))
.findFirst();
Or if the field holds a primitive value:
Optional<Integer> indexOfMatch = IntStream.range(0, yourList.size())
.filter(i -> valueYouAreLookingFor == yourList.get(i).getFieldYouAreChecking())
.findFirst();
If there is an element in the list that matches your predicate, indexOfMatch
will have the index of that element. If not, indexOfMatch
will be an empty Optional
.
Regarding whether an ArrayList is the appropriate structure, generally if you are working with a list of values, an implementation of List
is what you want. Whether it should be ArrayList
or some other implementation depends on details of what you are doing with the list. For small list sizes, it often doesn't really matter which implementation you use.

- 1
- 3
-
2Append `.orElse(-1)` to `findFirst()` and you'll get `-1` if not found, just like `List.indexOf` – julien.giband May 17 '21 at 21:41
I am iterating over the ArrayList and seeing whether the current value is the id value you want.
int yourValue = 25; //I am assuming it to be an int of value 25, you can keep it whatever you want.
for (int i = 0; i < yourArrayList.size(); i++)
{
if (yourArrayList.get(i) == yourValue)
{
return i; //returning the index value
}
}
return null; //this will run if the value doesn't exist.
Obviously, this would need to be inside a method that returns an integer that is the index. Above, yourArrayList
is the ArrayList you are using, and yourValue
is the value you need to find. It doesn't have to be an int.

- 376
- 1
- 11
well I switched to a vector from an array list but it did not really help but I did use a loop and the list size and just put the contact in a container each time so I could do my comparison it was kinda messy but I got the index that way.
static int SearchForContact(String ContactID) {
int temp = -1;
Contact searchCon;
for (int z = 0 ; z < contactVector.size(); z++)
{searchCon = contactVector.get(z);
if(searchCon.getId() == ContactID)
{temp = z;}
}
if (temp == -1) {
throw new IllegalArgumentException("Contact not found");
}
return temp;
}
-
Lol this is almost the same as my answer other than you used a vector. Cool though! – TheSj May 18 '21 at 00:31