given I have a list of items that all inherit from the same base class:
class Item {
protected String name;
public Item(String name) {
this.name = name;
}
getName() {
return name;
}
}
class ItemA extends Item {...}
class ItemB extends Item {...}
List itemList = Arrays.asList(new ItemA("itemA"), new ItemB("itemB"));
In my case I have no control over how these classes are implemented but I need to separate the list into two different lists containing the name of the respective element.
Here is the first try at a solution that contains lots of if and instanceof statements:
List itemAList = new ArrayList<>();
List itemBList = new ArrayList<>();
itemList.forEach(item -> {
if(item instanceof ItemA) {
itemAList.add(item.getName());
}
else if(item instanceof ItemB) {
itemBList.add(item.getName());
}
});
So this works but I gave it some thought on how to avoid the if statements. Since I'm using Java 8 I can do this:
List itemAList = itemList.stream()
.filter(ItemA.class::isInstance)
.map(item -> item.getName())
.collect(Collectors.toList());
List itemBList = itemList.stream()
.filter(ItemB.class::isInstance)
.map(item -> item.getName())
.collect(Collectors.toList());
This works as well but it means I have to process the list two times.
As I said I have no bearing on the implementation of the Item classes so what would be the best way to implement such a behavior?
Greetings
[edit:] Thank you for all the responses. I've learned something new today.
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)