How to use collect call in Java 8?

后端 未结 2 1050
梦谈多话
梦谈多话 2021-02-12 09:11

Lets say we have this boring piece of code that we all had to use:

ArrayList ids = new ArrayList();
for (MyObj obj : myList){
    ids.add         


        
2条回答
  •  感情败类
    2021-02-12 10:01

    I use a lot of collector blocks where I create an empty Array and fill it using a loop so I decided I need a utility class of my own not to write the same lines again ad again, here it is:

    public class Collections {
    
        public static  List collect(Set items, Function mapper) {
    
        return items.stream().map(mapper).collect(Collectors.toCollection(ArrayList::new));
    }
    

    }

    and use it like this

    List prods = Collections.collect(basket.getOrderItems(), OrderItem::getProduct);
    

    or like this

    List prods = Collections.collect(basket.getOrderItems(), (item)->item.getProduct().getId());
    

    Though it might look like much more easier to read, it seems streams are a little slower in these kind of scenarios, look here

提交回复
热议问题