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())));

Use Java lambda instead of ‘if else’

As it almost but not really matches Optional, maybe you might reconsider the logic: Java 8 has a limited expressiveness: Optional<Elem> element = … element.ifPresent(el -> System.out.println(“Present ” + el); System.out.println(element.orElse(DEFAULT_ELEM)); Here the map might restrict the view on the element: element.map(el -> el.mySpecialView()).ifPresent(System.out::println); Java 9: element.ifPresentOrElse(el -> System.out.println(“Present ” + el, () -> System.out.println(“Not …

Read more

Does Java 8 have cached support for suppliers?

There’s no built-in Java function for memoization, though it’s not very hard to implement it, for example, like this: public static <T> Supplier<T> memoize(Supplier<T> delegate) { AtomicReference<T> value = new AtomicReference<>(); return () -> { T val = value.get(); if (val == null) { val = value.updateAndGet(cur -> cur == null ? Objects.requireNonNull(delegate.get()) : cur); …

Read more

Java 8 modify stream elements

You must have some method/constructor that generates a copy of an existing SampleDTO instance, such as a copy constructor. Then you can map each original SampleDTO instance to a new SampleDTO instance, and collect them into a new List : List<SampleDTO> output = list.stream() .map(s-> { SampleDTO n = new SampleDTO(s); // create new instance …

Read more

Setting timezone for maven unit tests on Java 8

Short answer Java now reads user.timezone earlier, before surefire sets the properties in systemPropertyVariables. The solution is to set it earlier, using argLine: <plugin> … <configuration> <argLine>-Duser.timezone=UTC</argLine> Long answer Java initializes the default timezone, taking user.timezone into account the first time it needs it and then caches it in java.util.TimeZone. That now happens already when …

Read more