Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering collections with lambdaj

I have two classes like that:

public class Order{
    private Integer id;
    private List<Position> positions;
    ...
}

public class Position{
    private Integer id;
    private String content;
    ...
}

Now, I have a list with orders and want to get all orders that have positions with a specific content. At the moment i do it like that:

List<Order> orders = ... ;

List<Order> outputOrders = ... ;
for(Order order : orders){
    if(select(order.getPositions(), having(on(Position.class).getContent(),equalTo("Something"))).size() != 0){
        outputOrders.add(order);
    }
}

Is there a better way to do that with lambdaj?

Thanks in advance.

like image 570
Qri Avatar asked Mar 18 '13 08:03

Qri


People also ask

How will you run a filter on a collection?

You can filter Java Collections like List, Set or Map in Java 8 by using the filter() method of the Stream class. You first need to obtain a stream from Collection by calling stream() method and then you can use the filter() method, which takes a Predicate as the only argument.

How do you filter data in an ArrayList?

ArrayList removeIf() method in Java The removeIf() method of ArrayList is used to remove all of the elements of this ArrayList that satisfies a given predicate filter which is passed as a parameter to the method.


1 Answers

What about this one: use org.hamcrest.Matchers.hasItem?

List<Order> outputOrders =
        filter(having(on(Order.class).getPositions(),
                      hasItem(having(on(Position.class).getContent(),
                                     equalTo("Something")))),
               orders);
like image 87
longhua Avatar answered Sep 19 '22 16:09

longhua