Collections.binarySearch() .
Assuming cats are sorted by birthday, this will give the index of one of the cats with the correct birthday. From there, you can iterate back and forth until you click on another birthday.
If the list is long and / or not many cats share their birthday, this should be a significant win in direct iteration.
Here is the code I'm thinking of. Please note that I assume random access ; for a linked list, you are heavily obsessed with iterating. (Thanks to fred-o for pointing this out in the comments.)
List<Cat> cats = ...; // sorted by birthday List<Cat> catsWithSameBirthday = new ArrayList<Cat>(); Cat key = new Cat(); key.setBirthday(...); final int index = Collections.binarySearch(cats, key); if (index < 0) return catsWithSameBirthday; catsWithSameBirthday.add(cats.get(index)); // go backwards for (int i = index-1; i > 0; i--) { if (cats.get(tmpIndex).getBirthday().equals(key.getBirthday())) catsWithSameBirthday.add(cats.get(tmpIndex)); else break; } // go forwards for (int i = index+1; i < cats.size(); i++) { if (cats.get(tmpIndex).getBirthday().equals(key.getBirthday())) catsWithSameBirthday.add(cats.get(tmpIndex)); else break; } return catsWithSameBirthday;
source share