Tuesday, November 4, 2014

Learning Java 8

Comparator<Apple> c = Comparator.comparing((Apple a) -> a.getWeight());
inventory.sort(comparing((a) -> a.getWeight()));
inventory.sort(comparing(Apple::getWeight));
Comparator<Apple> c = Comparator.comparing(Apple::getWeight);
Function<String, String> addHeader = Letter::addHeader;
Function<String, String> transformationPipeline
  = addHeader.andThen(Letter::checkSpelling)
             .andThen(Letter::addFooter);
public double integrate(DoubleFunction<Double> f, double a, double b) {
      return (f.apply(a) + f.apply(b)) * (b-a) / 2.0;
}
Streams are an update to the Java API that lets you manipulate collections of data in a declarative way
streams can be processed in parallel transparently, without you having to write any multithreaded code!
List<String> lowCaloricDishesName =
               menu.parallelStream()
                   .filter(d -> d.getCalories() < 400)
                   .sorted(comparing(Dishes::getCalories))
                   .map(Dish::getName)
                   .collect(toList());
Because operations such as filter (or sortedmap, and collect) are available as high-level building blocks that don’t depend on a specific threading model, their internal implementation could be single-threaded or potentially maximize your multicore architecture transparently!
Map<Dish.Type, List<Dish>> dishesByType =
    menu.stream().collect(groupingBy(Dish::getType));
Collections are about data; streams are about computations.
  • Pipelining— This enables certain optimizations that we explain in the next chapter, such as laziness and short-circuiting
  • Internal iteration— In contrast to collections, which are iterated explicitly using an iterator, stream operations do the iteration behind the scenes for you.
You can consume a stream only once!
  • filtermap, and limit can be connected together to form a pipeline.
  • collect causes the pipeline to be executed and closes it.
menu.stream().forEach(System.out::println);
List<Dish> dishes = menu.stream()
                        .filter(d -> d.getCalories() > 300)
                        .skip(2)
                        .collect(toList());
List<Integer> dishNameLengths = menu.stream()
                                   .map(Dish::getName)
                                   .map(String::length)
                                   .collect(toList());
the flatMap method lets you replace each value of a stream with another stream and then concatenates all the generated streams into a single stream.
if(menu.stream().anyMatch(Dish::isVegetarian)){
Optional<Dish> dish =
  menu.stream()
      .filter(Dish::isVegetarian)
      .findAny();

Optional<Integer> firstSquareDivisibleByThree =
  someNumbers.stream()
             .map(x -> x * x)
             .filter(x -> x % 3 == 0)
             .findFirst(); // 9
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
reduce takes two arguments:
  • An initial value, here 0.
  • BinaryOperator<T> to combine two elements and produce a new value; here you use the lambda (a, b) -> a + b.
int product = numbers.stream().reduce(1, (a, b) -> a * b);
int sum = numbers.stream().reduce(0, Integer::sum);
Optional<Integer> max = numbers.stream().reduce(Integer::max);
Optional<Integer> min = numbers.stream().reduce(Integer::min);
long count = menu.stream().count();
int sum = numbers.parallelStream().reduce(0, Integer::sum);
String traderStr =
    transactions.stream()
                .map(transaction -> transaction.getTrader().getName())
                .distinct()
                .sorted()
                .collect(joining());
Optional<Transaction> smallestTransaction =
  transactions.stream()
              .min(comparing(Transaction::getValue));
Numeric streams
OptionalInt maxCalories = menu.stream()
                              .mapToInt(Dish::getCalories)
                              .max();

No comments:

Post a Comment