What implementation detail makes this code fail so easily?

First, it’s not failing reliably. I managed to have some runs where no exception occurred. This, however doesn’t imply that the resulting map is correct. It’s also possible that each thread witnesses its own value being successfully put, while the resulting map misses several mappings. But indeed, failing with a NullPointerException happens quite often. I …

Read more

Java 8 streams conditional processing

Java 8 streams weren’t designed to support this kind of operation. From the jdk: A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, “forked” streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. If you can …

Read more

Java Stream: divide into two lists by boolean predicate

Collectors.partitioningBy: Map<Boolean, List<Employee>> partitioned = listOfEmployees.stream().collect( Collectors.partitioningBy(Employee::isActive)); The resulting map contains two lists, corresponding to whether or not the predicate was matched: List<Employee> activeEmployees = partitioned.get(true); List<Employee> formerEmployees = partitioned.get(false); There are a couple of reasons to use partitioningBy over groupingBy (as suggested by Juan Carlos Mendoza): Firstly, the parameter of groupingBy is a Function<Employee, …

Read more

Join a list of object’s properties into a String

To retrieve a String consisting of all the ID’s separated by the delimiter “,” you first have to map the Person ID’s into a new stream which you can then apply Collectors.joining on. String result = personList.stream().map(Person::getId) .collect(Collectors.joining(“,”)); if your ID field is not a String but rather an int or some other primitive numeric …

Read more

Java Streams: group a List into a Map of Maps

You can group your data in one go assuming there are only distinct Foo: Map<String, Map<String, Foo>> map = list.stream() .collect(Collectors.groupingBy(f -> f.b.id, Collectors.toMap(f -> f.b.date, Function.identity()))); Saving some characters by using static imports: Map<String, Map<String, Foo>> map = list.stream() .collect(groupingBy(f -> f.b.id, toMap(f -> f.b.date, identity())));