Kion F Kion F - 3 months ago 5
Java Question

Selecting only elements with specific attributes from Java List

So lets say I have a list,

, and a class MyObject as such:

public class MyObject {
Type t;

Where 't' is a non-unique identifier. How would I select all elements from my list with a specific value for t? For my purpose I am trying to return a count of how many objects in the list have a specific value for t.

I am assuming there is some clean way of doing this in Java without using an explicit loop?


Streams are your friend:

List<MyObject> list = ...;
long count = -> e.getT().equals(<specific value>)).count();

You would of course need a way to access t, here I use getT() as an example.