java: Arrays.sort() with lambda expression

The cleanest way would be: Arrays.sort(months, Comparator.comparingInt(String::length)); or, with a static import: Arrays.sort(months, comparingInt(String::length)); However, this would work too but is more verbose: Arrays.sort(months, (String a, String b) -> a.length() – b.length()); Or shorter: Arrays.sort(months, (a, b) -> a.length() – b.length()); Finally your last one: Arrays.sort(months, (String a, String b) -> { return Integer.signum(a.length() – … Read more

Differences between Collectors.toMap() and Collectors.groupingBy() to collect into a Map

TLDR : To collect into a Map that contains a single value by key (Map<MyKey,MyObject>), use Collectors.toMap(). To collect into a Map that contains multiple values by key (Map<MyKey, List<MyObject>>), use Collectors.groupingBy(). Collectors.toMap() By writing : chargePoints.stream().collect(Collectors.toMap(Point::getParentId, c -> c)); The returned object will have the Map<Long,Point> type. Look at the Collectors.toMap() function that you … Read more

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