Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java, search for an element, if not found, add it

I am pretty new to streams.

I would like to stream the geometries EC_Geometry arraylist and if the EC_Geometry element is not present (or better equals never returns true), then I add it.

public void init(GL3 gl3, EC_Mesh mesh) {

    geometries.stream()
            .filter(geometry -> mesh.getGeometry().equals(geometry))
            .findAny()
            .orElse(..?);
}

But I am stuck at the last line

How can I solve it using streams?

Please note that equals is a method I wrote checking if the geometry is the same (i.e: if the triangles correspond)

like image 437
elect Avatar asked Jun 17 '16 08:06

elect


1 Answers

orElse will always run even if the value returned isn't used so it is preferable to use orElseGet here which will only run if nothing is found.

 geometries.stream()
            .filter(geometry -> mesh.getGeometry().equals(geometry))
            .findAny()
            .orElseGet(() -> {
                geometries.add(mesh.getGeometry());
                return mesh.getGeometry();
            });
like image 175
Olayinka Avatar answered Sep 19 '22 09:09

Olayinka