Monday, February 27, 2023

Java 8 Streams revisited

Java 8 has been around for a long time now and its Streams was one of its main new feature, but I doubt too many people actually make a lot of use of it. These can be powerful one liners that let you combine operations.
  List  myList = Arrays.asList(4,56,1,55,12,46);
  System.out.println("original list: "+myList);

  List myListFiltered = myList.stream().filter( n -> n%2 ==0).collect(Collectors.toList());
  System.out.println("even filter: "+myListFiltered);

  long countEven = myList.stream().filter(n -> n %2 ==0).count();
  System.out.println("count of even: "+countEven);

  System.out.println("max: "+  myList.stream().max(Integer::compare).get());
  System.out.println("avg: "+  myList.stream().mapToInt(Integer::intValue).average().getAsDouble());
  System.out.println("sum: "+  myList.stream().mapToInt(i->i).sum());
  System.out.println("sorted: "+myList.stream().sorted().collect(Collectors.toList()));


  List names  = Arrays.asList("ryu","ken", "guile", "chun li", "ryu", "ken");
  System.out.println("some names: "+names);
  List upper = names.stream().map(String::toUpperCase).distinct().sorted().collect(Collectors.toList());
  System.out.println("Sorted and upper and distinct: "+upper);
  
Output
  original list: [4, 56, 1, 55, 12, 46]
even filter: [4, 56, 12, 46]
count of even: 4
max: 56
avg: 29.0
sum: 174
sorted: [1, 4, 12, 46, 55, 56]
some names: [ryu, ken, guile, chun li, ryu, ken]
Sorted and upper and distinct: [CHUN LI, GUILE, KEN, RYU]

No comments: