Kion F Kion F - 5 months ago 7
Java Question

Selecting only elements with specific attributes from Java List

So lets say I have a list,

List<MyObject>
, 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?

Answer

Streams are your friend:

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

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