简体   繁体   中英

Pull out certain objects from an ArrayList of Interfaces in Java?

I need to call a method from a few objects in an ArrayList that is typed by an interface (Here we will call it interface).

ArrayList<Interface> obj = new ArrayList();

obj.stream().forEachOrdered((o) -> {
  if (/*If o extends ObjectA then run this next line*/) {
    o.methodCallNotInTheInterface();
        }
    });

My problem is o can only ever see the methods and variables of the interface and nothing else.

I think you might be looking for the instanceof key word.

if (o instanecof ObjectA) { ...}

That said, usage of instanceof is often indicating a code smell , and your design should probably not have a method that is not implemented, and if for some reason it does have such method, make it throw an exception ( NotImplementedException ).

You can use the instanceof operator to decide whether your object is of the correct type:

List<Interface> obj = new ArrayList<>();
obj.stream().forEachOrdered(o -> {
    if (o instanceof ObjectA) {
        ((ObjectA) o).methodCallNotInTheInterface();
    }
});

Note that instanceof also returns false if o is null, so you don't need to check for that.

Check first the type of o :

if (o instanecof ObjectA)

then cast o to type ObjectA :

((ObjectA)o).method();

As you're using a stream, you could use a predicate to filter the values you want and then apply a function to the filtered values. This function would simply cast values to the desired class.

Consider the following list of numbers:

List<Number> list = new ArrayList<>(Arrays.asList(1, new BigDecimal("2.22"), 3l));

Then, if you only needed to call a method on BigDecimal instances, you could do it this way:

list.stream()
    .filter(n -> n instanceof BigDecimal)
    .map(n -> (BigDecimal) n)
    .forEachOrdered(n -> System.out.println(n.pow(2))); // 4.9284

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM