First using stream we will Iterate through hospitals list,
find out the hospital from the list whose name equals currentHospital name, take out the first result using findFirst.
Since the result may be or may not be available it returns Optional.
So on Optional, we will say if it's (the hospital object which we were looking for) present we will get the hospital out of it using the get method
Optional<Hospital> result = hospitals.stream().filter(h -> h.nameHospital.equals(currentHospital)).findFirst();
if(result.isPresent()){
Hospital hospital = result.get();
}
Answer from navnath on Stack Overflowjava - Using indexOf() method for ArrayList of objects - Stack Overflow
A better way to find the index of an element in an array?
Arraylist indexof
Java ArrayList IndexOf - Finding Object Index - Stack Overflow
Videos
Currently the best way I have found is to typecast the array into an ArrayList, and using ArrayList's method .indexOf to get the index, for e.g:
import java.util.Arrays;
int[] arr = {2,3,4,5};
Arrays.asList(arr).indexOf(4); // returns 2Is this the best way? Or unnecessary wrapping?
The indexOf() method does go through the entire list. Here's an excerpt from Java 7 source code:
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}
It'd be better to let Java go through it than write it yourself. Just make sure that your equals method is sufficient at finding the object you want. You'll also want to override hashCode() as well.
I won't write your equals method out, but I would recommend that you at least:
- Check for null
- Test if the instances you're comparing are the same
- You don't need to do
if(boolean_expr) { return true; }; just return the boolean expression. - Make sure you're actually overriding your
equalsmethod - the signature of that requires anObjectparameter, notDate.
The signature of your equals method is wrong. You are not overriding the equals in Object, but just overloading it.
To override the behavior of equals method in Object, your signature must exactly match with the one in Object. Try this:
public boolean equals(Object o) {
if(!(o instanceof Data)) return false;
Data other = (Data) o;
return (this.k == other.k && this.l == other.l);
}
In addition, as others suggested, it is a good idea to override hashCode method also for your object to work correctly in map based collections.