Kion F Kion F - 1 year ago 66
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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download