How to implement a Java stream?

The JDK’s standard implementation of Stream is the internal class java.util.stream.ReferencePipeline, you cannot instantiate it directly. Instead you can use java.util.stream.Stream.builder(), java.util.stream.StreamSupport.stream(Spliterator<T>, boolean) and various1, 2 other static factory methods to create an instance of the default implementation. Using a spliterator is probably the most powerful approach as it allows you to provide objects lazily … Read more

Merging two Map with Java 8 Stream API

@Test public void test14() throws Exception { Map<String, Integer> m1 = ImmutableMap.of(“a”, 2, “b”, 3); Map<String, Integer> m2 = ImmutableMap.of(“a”, 3, “c”, 4); Map<String, Integer> mx = Stream.of(m1, m2) .map(Map::entrySet) // converts each map into an entry set .flatMap(Collection::stream) // converts each set into an entry stream, then // “concatenates” it in place of the … Read more

Java 8 stream map to list of keys sorted by values

You say you want to sort by value, but you don’t have that in your code. Pass a lambda (or method reference) to sorted to tell it how you want to sort. And you want to get the keys; use map to transform entries to keys. List<Type> types = countByType.entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getValue)) .map(Map.Entry::getKey) .collect(Collectors.toList());

Is it possible to cast a Stream in Java 8?

I don’t think there is a way to do that out-of-the-box. A possibly cleaner solution would be: Stream.of(objects) .filter(c -> c instanceof Client) .map(c -> (Client) c) .map(Client::getID) .forEach(System.out::println); or, as suggested in the comments, you could use the cast method – the former may be easier to read though: Stream.of(objects) .filter(Client.class::isInstance) .map(Client.class::cast) .map(Client::getID) .forEach(System.out::println);

Java 8 grouping using custom collector?

When grouping a Stream with Collectors.groupingBy, you can specify a reduction operation on the values with a custom Collector. Here, we need to use Collectors.mapping, which takes a function (what the mapping is) and a collector (how to collect the mapped values). In this case the mapping is Person::getName, i.e. a method reference that returns … Read more