Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you check if a list contains an element that matches some predicate?

Tags:

java

arraylist

I have an ArrayList containing objects which have 4 parameters (x, y, iD and myType). I want to verify if there are objects in this ArrayList which have particular coordinates, independently of their iD and myType parameters. I wanted to use Arrays.asList(yourArray).contains(yourValue) but it is when the object has only one parameter.

Here is the whole code:

public class MyObject {

  public float x;
  public float y;
  public int iD;
  public String myType;


  public MyObject (float x, float y, int iD, String myType) 
  {
    this.myType = myType;
    this.iD = iD;
    this.x = x;
    this.y = y;
  }
  @Override
    public String toString() {
    return ("[iD="+iD+" x="+x+" y="+y +" type="+myType+"]");
  }
}


ArrayList<MyObject> myArrayList = new ArrayList<MyObject>();

void setup() 
{
  size(100, 60);
  myArrayList.add(new MyObject(3.5, 4.5, 6, "a"));
  myArrayList.add(new MyObject(5.4, 2.6, 4, "b"));
}

For example, if I want to verify if there is an object which has the coordinates (3.5, 4.5), how should I proceed ? Is there an easy way to do this ?

thanks for your help

like image 968
Graham Slick Avatar asked Mar 16 '23 09:03

Graham Slick


1 Answers

The javadoc of List#contains(Object) states

Returns true if this list contains the specified element.

That's not what you're trying to do here. You're not specifying an element, you want to specify properties of an element. Don't use this method.

The long form solution is to iterate over the elements in the List and check them individually, returning true as soon as you find one, or false when you run out of elements.

public boolean findAny(ArrayList<MyObject> myArrayList, float targetX) {
    for (MyObject element : myArrayList) {
        if (element.x == targetX) { // whatever condition(s) you want to check
            return true;
        }
    }
    return false;
}

Since Java 8, there's a better way to do this using Stream#anyMatch(Predicate) which

Returns whether any elements of this stream match the provided predicate.

Where the given Predicate is simply a test for the properties you're looking for

return myArrayList.stream().anyMatch((e) -> e.x == targetX); 

Regarding equality checks for floating point values, see the following:

  • What's wrong with using == to compare floats in Java?
  • Test for floating point equality. (FE_FLOATING_POINT_EQUALITY)
like image 65
Sotirios Delimanolis Avatar answered Mar 17 '23 23:03

Sotirios Delimanolis