osanger
osanger

Reputation: 2352

java find a list element by its class

i'm using soot to analyse Java-Code. Because Soot still got no full Java 8-Support im working with Java 7. I need to get the first element of the class LinkedRValueBox.

My actual list looks like this:

[ImmediateBox(0), ImmediateBox(1), LinkedRValueBox(0 + 1)]

Of course i could iterate the list and proof every Element with instanceof. I couldn't find any solution for this issue.

Upvotes: 2

Views: 170

Answers (1)

Donald Raab
Donald Raab

Reputation: 6686

If you're open to using a third-party library, with Eclipse Collections version 7.x, you can either use detect with Predicates.instanceOf() or if you want to filter the list, can use selectInstancesOf(). Here's an example which uses different types of Number, and detects the first instance of Double.

MutableList<? extends Number> list =
        Lists.mutable.with(new Integer(0), new Long(0), new Double(0));
Number detect = list.detect(Predicates.instanceOf(Double.class));
MutableList<Double> doubles = list.selectInstancesOf(Double.class);
Double first = doubles.getFirst();
Assert.assertTrue(detect instanceof Double);
Assert.assertSame(detect, first);

Eclipse Collection version 8.x compiles using Java 8, but version 7.x works with Java 5 or greater.

Note: I am a committer for Eclipse Collections.

Upvotes: 1

Related Questions