JAVA getitemlist,Java 8 Stream在列表中查找元素

I have the following class:

public class Item {

int id;

String name;

// few other fields, contructor, getters and setters

}

I have a list of Items. I want to iterate through the list and find the instance which has a particular id. I'm trying to do it through streams.

public void foobar() {

List items = getItemList();

List ids = getIdsToLookup();

int id, i = ids.size() - 1;

while (i >= 0) {

id = ids.get(i);

Optional item = items

.stream()

.filter(a -> a.getId() == id)

.findFirst();

// do stuff

i--;

}

}

Is this the best way to iterate over the list and get the element I need? Also, I get an error on the filter line for id which says variables used in lambda expressions must be final or effectively final. Maybe I can define id inside the while loop, that should get rid of the exception. Thanks.

解决方案

If you have lots of ids to search, it's recommended to use a solution which does it in a single pass rather than doing a linear search for each id:

Map> map=ids.stream()

.collect(Collectors.toMap(id -> id, id -> Optional.empty()));

items.forEach(item ->

map.computeIfPresent(item.getId(), (i,o)->o.isPresent()? o: Optional.of(item)));

for(ListIterator it=ids.listIterator(ids.size()); it.hasPrevious();) {

map.get(it.previous()).ifPresent(item -> {

// do stuff

});

}

The first statement simply create a map out of the ids list, mapping each search id to an empty Optional.

The second statement iterates over the items using forEach and for each item, it checks whether there’s a mapping from its id to an empty Optional and will replace it with an Optional encapsulating the item, if there is such a mapping, all in one operation, computeIfPresent.

The last for loop iterates backwards over the ids list, as you wished to process them in that order and perform the action if there’s a non-empty Optional. Since the map was initialized with all ids found in the list, get will never return null, it will return an empty Optional, if the id was not found in the items list.

That way, assuming that the Map’s lookup has O(1) time complexity, which is the case in typical implementations, the net time complexity changed from O(m×n) to O(m+n)…

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值