Reputation: 275
I am trying to iterate over an ArrayList
and want to find out an element. In list thousand of items are there so its taking much time to find. So, Can any one please suggest efficient and quick search. Code is below:
private FoodItem getFoodItem(List<FoodItem> foodItemList, String foodItemId) {
if (foodItemId == null || foodItemList == null || foodItemList.isEmpty()) {
return null;
}
for (FoodItem foodItem : foodItemList) {
if (foodItem == null) {
continue;
}
if (foodItem.getId().equals(foodItemId)) {
return foodItem;
}
}
return null;
}
Upvotes: 0
Views: 192
Reputation: 2773
Probably parallel stream will help
foodItemList.parallelStream().findAny(foodItem->foodItem.getId().equals(foodItemId))
It returns Optional<FoodItem>
Upvotes: 0
Reputation: 19926
As already mentioned by @Eran in the comments. The use of a Map
might be the best option, regarding the look up with the Id
.
For conversion from a List
to a Map
you can make use of the Java8 Stream API:
Map<String, FoodItem> map = foodList.stream()
.collect(Collectors.toMap(FoodList::getId, Function.identity());
Note: this should be done once and not for every lookup.
And then with the lookup:
public FoodItem getFoodItem(Map<String, FoodItem> map, String foodItemId){
if (foodItemId == null || foodItemList == null || foodItemList.isEmpty()) {
return null;
}
return map.get(foodItemId); // returns null if it doesn't exists
}
Upvotes: 1
Reputation: 503
If you NEED to have a List, you probably want it to be ordered on insertion time (depending on how many inserts vs search you perform, because ordered insert is slower of course) and then perform some binary search.
Or even better, use a HashMap if you don't need a list (or even, a LinkedHashMap if you need predictable order).
Upvotes: 0