Friday, August 22, 2014

Java 8 Lambdas - examples

Group by and counting

List<String> strings = Arrays.asList("rami", "ida", "maya", "ida", "ida", "rami");
 Map<String, Long> collect = strings.stream().collect(Collectors.groupingBy((e) ->                                                                                                       e,Collectors.counting()));


Generate random numbers

 ThreadLocalRandom.current().longs().mapToObj(Long::toHexString).limit(10).sorted()


Filter and count
 long num = strList.stream().filter(x -> x.length()> 3).count();



PartitionBy

Map<Boolean, List<String>> collect1 = Arrays.asList("rami", "ida", "maya", "ida", "ida", "rami").stream().collect(Collectors.partitioningBy((x) -> x.startsWith("r")));

Result:
{false=[ida, maya, ida, ida], true=[rami, rami]}

No comments:

Post a Comment