@bobnoordam

Sorting and selection with the streams API

The common question: How do i make a selection from an arraylist in a simple way. Answer: use the streams api that has been around since forever.

Assume the very simple data class B

public class B {

    private int Nummer;

    public int getNummer() {
        return Nummer;
    }

    public B(int nummer) {
        Nummer = nummer;
    }
}

And let’s put some very simple data in it:

        ArrayList<B> blist = new ArrayList<>(); // prefer: List<B> blist = new ArrayList<>(); so you can swap list types if needed later on
        blist.add(new B(101));
        blist.add(new B(20));
        blist.add(new B(33));
        blist.add(new B(4));

Selecting with an arraylist as target

        // .stream() converts to a stream
        // .filter(...) applies the selection you want to make
        // .collect(...) converts the stream to whatever you need, in this case an arraylist implementation
        System.out.println("arraylist (inplementation)");
        ArrayList<B> myquery = blist.stream().filter(x -> x.getNummer() %2 ==0).collect(Collectors.toCollection(ArrayList::new));
        for(B item : myquery){
            System.out.println(item.getNummer());
        }

Or, using a generic List<> to keep your options more open:

        // Target is a generic List<> into the stream
        System.out.println("generic list (interface)");
        List<B> myquery2 = blist.stream().filter(x->x.getNummer() %2 == 0).collect(Collectors.toList());
        for(B item : myquery2){
            System.out.println(item.getNummer());
        }

Let’s do some simple sorting on a property while at it

        // simple sort
        System.out.println("sorted");
        List<B> myquery3 = blist.stream().sorted(Comparator.comparingInt(B::getNummer)).collect(Collectors.toList());
        for(B item : myquery3){
            System.out.println(item.getNummer());
        }

And reversed for good meassure

        // reversed
        System.out.println("reversed sort");
        List<B> myquery4 = blist.stream().sorted(Comparator.comparingInt(B::getNummer).reversed()).collect(Collectors.toList());
        for(B item : myquery4){
            System.out.println(item.getNummer());
        }