Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 …

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading