java separate_Java 8 separate list elements by class

这篇博客讨论了如何在Java 8中避免使用if和instanceof语句来分离继承自同一基类的列表。作者提供了一种使用Stream API的解决方案,虽然它需要遍历列表两次,但简化了代码。文章寻求最佳实践来处理此类问题,特别是在没有对子类实现控制的情况下。
摘要由CSDN通过智能技术生成

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值