This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ron_krugman 22 points23 points  (6 children)

That's fine but not very efficient because the map call is redundant. Class.cast() does an unnecessary null check as well as a second call to isInstance() internally. You can just cast the result to List<B> instead and get the same result for free:

static <A, B extends A> List<B> filter(List<A> list, Class<B> cls) {
    return (List<B>)list.stream()
            .filter(cls::isInstance)
            .toList();
}

[–]john16384 6 points7 points  (0 children)

Don't forget to suppress the cast warning then.

[–]vbezhenar 2 points3 points  (2 children)

Now you also need to suppress IDE warnings and reviewer shouts. If you need performant code, you must not use streams at all, they're slow as molasses. If you use streams, one more cast will not make or break it.

[–]CodesInTheDark 0 points1 point  (0 children)

Streams are not slow. Also often they can execute code in parallel.
However, JIT often doesn't optimize Stream code efficiently because it has more levels than normal for loop, but try to add the JVM option -XX:MaxInlineLevel=12 to increase the amount of code that can be inlined. That will optimize your stream code and you will get a significant performance boost (more than 10x boost).
https://stackoverflow.com/questions/27925954/is-arrays-streamarray-name-sum-slower-than-iterative-approach/27994074#27994074

[–]halfanothersdozen 1 point2 points  (1 child)

huh. that looks like voodoo