public static void main(String... args) {

    System.out.println("Filtering with predicate");
    System.out.println("converte a stream to a List with Stream.collect(toList())");
    // Filtering with predicate
    List<Dish> vegetarianMenu = menu.stream().filter(Dish::isVegetarian).collect(toList());

    vegetarianMenu.forEach(System.out::println);

    System.out.println("Fitring even element and distinct");
    // Filtering unique elements
    List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
    numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);

    System.out.println("Limiting a Stream to X elements limit(x)");
    // Truncating a stream
    List<Dish> dishesLimit3 =
        menu.stream().filter(d -> d.getCalories() > 300).limit(3).collect(toList());

    dishesLimit3.forEach(System.out::println);

    System.out.println("Skiping X first elements in a stream skip(X)");
    // Skipping elements
    List<Dish> dishesSkip2 =
        menu.stream().filter(d -> d.getCalories() > 300).skip(2).collect(toList());

    dishesSkip2.forEach(System.out::println);
  }
Beispiel #2
1
  public static void main(String... args) {

    List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
    numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);

    numbers.stream().limit(20).forEach(System.out::println);
  }
Beispiel #3
0
  public static void main(String... args) {

    List<Integer> numbers = Arrays.asList(3, 4, 5, 1, 2);

    Arrays.stream(numbers.toArray()).forEach(System.out::println);
    int calories = Dish.menu.stream().mapToInt(Dish::getCalories).sum();
    System.out.println("Number of calories:" + calories);

    // max and OptionalInt
    OptionalInt maxCalories = Dish.menu.stream().mapToInt(Dish::getCalories).max();

    int max;
    if (maxCalories.isPresent()) {
      max = maxCalories.getAsInt();
    } else {
      // we can choose a default value
      max = 1;
    }
    System.out.println(max);

    // numeric ranges
    IntStream evenNumbers = IntStream.rangeClosed(1, 100).filter(n -> n % 2 == 0);

    System.out.println(evenNumbers.count());

    Stream<int[]> pythagoreanTriples =
        IntStream.rangeClosed(1, 100)
            .boxed()
            .flatMap(
                a ->
                    IntStream.rangeClosed(a, 100)
                        .filter(b -> Math.sqrt(a * a + b * b) % 1 == 0)
                        .boxed()
                        .map(b -> new int[] {a, b, (int) Math.sqrt(a * a + b * b)}));

    pythagoreanTriples.forEach(t -> System.out.println(t[0] + ", " + t[1] + ", " + t[2]));
  }
Beispiel #4
0
 public static void main(String[] args) {
   Set<String> distinctWords = Arrays.asList(args).stream().collect(Collectors.toSet());
   System.out.println(distinctWords.size() + " distinct words: " + distinctWords);
 }
Beispiel #5
0
public class TodaysSales {
  public static final List<Sale> sales =
      Arrays.asList(
          new Sale(
              Store.KANSAS_CITY,
              new Date(),
              Optional.of("Sarah"),
              Arrays.asList(new Item("carrot", 12.00))),
          new Sale(
              Store.ST_LOUIS,
              new Date(),
              Optional.empty(),
              Arrays.asList(
                  new Item("carrot", 12.00), new Item("lizard", 99.99), new Item("cookie", 1.99))),
          new Sale(
              Store.ST_LOUIS,
              new Date(),
              Optional.of("Jamie"),
              Arrays.asList(new Item("banana", 3.49), new Item("cookie", 1.49))));

  static Stream<Sale> saleStream() {
    return RandomSale.streamOf(10000);
  }

  public static void main(String[] args) {
    // how many sales?
    long saleCount = saleStream().count();
    System.out.println("Count of sales: " + saleCount);

    // any sales over $100?
    Supplier<DoubleStream> totalStream = () -> saleStream().mapToDouble(Sale::total);
    boolean bigSaleDay = totalStream.get().anyMatch(total -> total > 100.00);
    System.out.println("Big sale day? " + bigSaleDay);

    // maximum sale amount?
    DoubleSummaryStatistics stats = totalStream.get().summaryStatistics();
    System.out.println("Max sale amount: " + stats.getMax());
    System.out.println("Stats on total: " + stats);

    // how many items were sold today?
    Supplier<Stream<Item>> itemStream = () -> saleStream().flatMap(sale -> sale.items.stream());
    long itemCount = itemStream.get().count();
    System.out.println("Count of items: " + itemCount);

    // which different items were sold today?
    String uniqueItems =
        itemStream.get().map(item -> item.identity).distinct().collect(Collectors.joining(" & "));
    System.out.println("Distinct items: " + uniqueItems);

    // summarize sales by store
    ConcurrentMap<String, DoubleSummaryStatistics> summary =
        saleStream()
            .parallel()
            .collect(
                Collectors.groupingByConcurrent(
                    sale -> Thread.currentThread().getName(),
                    Collectors.summarizingDouble(Sale::total)));
    System.out.println("Summary by thread: " + summary);
    summary
        .keySet()
        .stream()
        .sorted()
        .forEach(store -> System.out.println(store + " stats: " + summary.get(store)));
  }
}
public class BestPriceFinder {

  private final List<Shop> shops =
      Arrays.asList(
          new Shop("BestPrice"),
          new Shop("LetsSaveBig"),
          new Shop("MyFavoriteShop"),
          new Shop("BuyItAll"),
          new Shop("ShopEasy"));

  private final Executor executor =
      Executors.newFixedThreadPool(
          shops.size(),
          new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
              Thread t = new Thread(r);
              t.setDaemon(true);
              return t;
            }
          });

  /*
      public List<String> findPriceSequential(String product) {
          return shops.stream()
                  .map(shop -> shop.getName() + " price is " + shop.calculatePrice(product))
                  .collect(Collectors.<String>toList());
      }

      public List<String> findPriceParallel(String product) {
          return shops.parallelStream()
                  .map(shop -> shop.getName() + " price is " + shop.calculatePrice(product))
                  .collect(Collectors.<String>toList());
      }

      public List<String> findPrice(String product) {
          List<CompletableFuture<String>> priceFutures =
                  shops.stream()
                  .map(shop -> CompletableFuture.supplyAsync(() -> shop.getName() + " price is " + shop.calculatePrice(product)))
                  .collect(Collectors.<CompletableFuture<String>>toList());

          List<String> prices = priceFutures.stream()
                  .map(CompletableFuture::join)
                  .collect(Collectors.<String>toList());
          return prices;
          //return sequence(priceFutures).join();
      }
  /*/
  public List<String> findPriceSequential(String product) {
    return shops
        .stream()
        .map(shop -> shop.getPrice(product))
        .map(Quote::parse)
        .map(Discount::applyDiscount)
        .collect(Collectors.<String>toList());
  }

  public List<String> findPriceParallel(String product) {
    return shops
        .parallelStream()
        .map(shop -> shop.getPrice(product))
        .map(Quote::parse)
        .map(Discount::applyDiscount)
        .collect(Collectors.<String>toList());
  }

  public List<String> findPrice(String product) {
    List<CompletableFuture<String>> priceFutures =
        findPriceStream(product).collect(Collectors.<CompletableFuture<String>>toList());

    return priceFutures.stream().map(CompletableFuture::join).collect(Collectors.<String>toList());
  }

  public Stream<CompletableFuture<String>> findPriceStream(String product) {
    return shops
        .stream()
        .map(shop -> CompletableFuture.supplyAsync(() -> shop.getPrice(product), executor))
        .map(future -> future.thenApply(Quote::parse))
        .map(
            future ->
                future.thenCompose(
                    quote ->
                        CompletableFuture.supplyAsync(
                            () -> Discount.applyDiscount(quote), executor)));
  }

  public void printPricesStream() {
    long start = System.nanoTime();
    CompletableFuture[] futures =
        findPriceStream("myPhone")
            .map(
                f ->
                    f.thenAccept(
                        s ->
                            System.out.println(
                                s
                                    + " (done in "
                                    + ((System.nanoTime() - start) / 1_000_000)
                                    + " msecs)")))
            .toArray(size -> new CompletableFuture[size]);
    CompletableFuture.allOf(futures).join();
  }
}