How do I get a single item from a Java Collection?

If we have a class that looks like this:

public class Item {
    public Item(String itemId, String description) {
        this.itemId = itemId;
        this.description = description;
    }

    private final String itemId;
    private final String description;

    public String getItemId() {
        return this.itemId;
    }

    public String getDescription() {
        return this.description;
    }
}

And I have a Collection of those objects

Collection<Item> items = FXCollections.observableArrayList();

And now I want to pull from the collection, the Item that has a specific itemId …

How can I do that without iterating through the Collection so that I can have a method that looks like this:

//pseudocode
public Item getItem(String itemId) {
    return Item from Collection with itemId == itemId; 
}

Instead of this

public Item getItem(String itemId) {
    for(Item item : items) {
        if (item.getItemId().equals(itemId)) return item;
    }
    return null;
}

>Solution :

return items.stream().filter(i->i.getItemId().equals(itemId)).findFirst().get();

Leave a Reply