Java Stream How to - Filter, then sort, then map and convert to list








Question

We would like to know how to filter, then sort, then map and convert to list.

Answer

import java.util.*;
import java.util.stream.Collectors;
/*w w  w  . ja v a  2s . c  o m*/
class DataSet {
        public final String name;
        public final Set<Integer> data;
        public DataSet(final String name, final Integer ... seasons) {
            this.name = name;
            this.data = Collections.unmodifiableSet(new TreeSet<>(Arrays.asList(seasons)));
        }
}
public class Main {
    private static final List<DataSet> CHARACTERS = Collections.unmodifiableList(Arrays.asList(
            new DataSet("A", 1, 2, 3, 4, 5),
            new DataSet("B", 2, 3, 4, 5),
            new DataSet("C", 1, 2, 3),
            new DataSet("D", 3, 4),
            new DataSet("E", 3, 4, 5),
            new DataSet("F", 5),
            new DataSet("G", 2),
            new DataSet("H", 1, 2),
            new DataSet("I", 1, 2, 3)
    ));

    public static void main(final String ... args) {
        final List<String> docks = CHARACTERS.stream()
                        .filter(c -> c.data.contains(2))
                        .sorted((a, b) -> a.data.size() - b.data.size())
                        .map(c -> c.name)
                        .collect(Collectors.toList());

        System.out.println(docks);
    }

}

The code above generates the following result.