elect elect - 5 months ago 8
Java Question

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)

Answer

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();
            });
Comments