コード例 #1
0
 /**
  * of the summary of the MonetaryAmount
  *
  * @param currencyUnit the target {@link javax.money.CurrencyUnit}
  * @return the MonetarySummaryStatistics
  */
 public static Collector<MonetaryAmount, MonetarySummaryStatistics, MonetarySummaryStatistics>
     summarizingMonetary(CurrencyUnit currencyUnit) {
   Supplier<MonetarySummaryStatistics> supplier =
       () -> new DefaultMonetarySummaryStatistics(currencyUnit);
   return Collector.of(
       supplier, MonetarySummaryStatistics::accept, MonetarySummaryStatistics::combine);
 }
コード例 #2
0
 public static <T> Collector<? super T, ?, T> reducing(BinaryOperator<T> op) {
   Supplier<SettableValue<T>> supplier = SettableValue::new;
   BiConsumer<SettableValue<T>, T> accumulator = (box, ele) -> box.set(ele);
   BinaryOperator<SettableValue<T>> combiner = SettableValue::merge;
   Function<SettableValue<T>, T> finisher = SettableValue::get;
   return Collector.of(supplier, accumulator, combiner, finisher);
 }
コード例 #3
0
ファイル: GuavaUtils.java プロジェクト: rosmo/aurora
 /** Collector to create a Guava ImmutableList. */
 public static <T> Collector<T, ?, ImmutableList<T>> toImmutableList() {
   return Collector.of(
       ImmutableList.Builder<T>::new,
       ImmutableList.Builder::add,
       (l, r) -> l.addAll(r.build()),
       ImmutableList.Builder::build);
 }
コード例 #4
0
 /**
  * of MonetaryAmount group by MonetarySummary
  *
  * @return the MonetarySummaryStatistics
  */
 public static Collector<
         MonetaryAmount, GroupMonetarySummaryStatistics, GroupMonetarySummaryStatistics>
     groupBySummarizingMonetary() {
   return Collector.of(
       GroupMonetarySummaryStatistics::new,
       GroupMonetarySummaryStatistics::accept,
       GroupMonetarySummaryStatistics::combine);
 }
コード例 #5
0
  /**
   * of the summary of the MonetaryAmount
   *
   * @param currencyUnit the target {@link javax.money.CurrencyUnit}
   * @return the MonetarySummaryStatistics
   */
  public static Collector<MonetaryAmount, MonetarySummaryStatistics, MonetarySummaryStatistics>
      summarizingMonetary(CurrencyUnit currencyUnit, ExchangeRateProvider provider) {

    Supplier<MonetarySummaryStatistics> supplier =
        () -> new ExchangeRateMonetarySummaryStatistics(currencyUnit, provider);
    return Collector.of(
        supplier, MonetarySummaryStatistics::accept, MonetarySummaryStatistics::combine);
  }
コード例 #6
0
ファイル: GuavaUtils.java プロジェクト: rosmo/aurora
 /** Collector to create a Guava ImmutableSet. */
 public static <T> Collector<T, ?, ImmutableSet<T>> toImmutableSet() {
   return Collector.of(
       ImmutableSet.Builder<T>::new,
       ImmutableSet.Builder::add,
       (l, r) -> l.addAll(r.build()),
       ImmutableSet.Builder::build,
       UNORDERED);
 }
コード例 #7
0
 public static <T> Collector<T, ?, ObservableList<T>> toObservableList() {
   return Collector.of(
       (Supplier<ObservableList<T>>) FXCollections::observableArrayList,
       List::add,
       (left, right) -> {
         left.addAll(right);
         return left;
       });
 }
コード例 #8
0
ファイル: ExportProfiles.java プロジェクト: nurv/fenixedu-ist
 public static <T extends JsonElement> Collector<T, JsonArray, JsonArray> toJsonArray() {
   return Collector.of(
       JsonArray::new,
       (array, element) -> array.add(element),
       (one, other) -> {
         one.addAll(other);
         return one;
       },
       Characteristics.IDENTITY_FINISH);
 }
コード例 #9
0
 /**
  * Returns a {@link java.util.stream.Collector} which may be used in conjunction with {@link
  * java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link
  * javaslang.collection.HashMap}.
  *
  * @param <K> The key type
  * @param <V> The value type
  * @return A {@link javaslang.collection.HashMap} Collector.
  */
 public static <K, V> Collector<Tuple2<K, V>, ArrayList<Tuple2<K, V>>, HashMap<K, V>> collector() {
   final Supplier<ArrayList<Tuple2<K, V>>> supplier = ArrayList::new;
   final BiConsumer<ArrayList<Tuple2<K, V>>, Tuple2<K, V>> accumulator = ArrayList::add;
   final BinaryOperator<ArrayList<Tuple2<K, V>>> combiner =
       (left, right) -> {
         left.addAll(right);
         return left;
       };
   final Function<ArrayList<Tuple2<K, V>>, HashMap<K, V>> finisher = HashMap::ofAll;
   return Collector.of(supplier, accumulator, combiner, finisher);
 }
コード例 #10
0
ファイル: Tree.java プロジェクト: top-projects/javaslang
 /**
  * Returns a {@link java.util.stream.Collector} which may be used in conjunction with {@link
  * java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link
  * javaslang.collection.Tree}.
  *
  * @param <T> Component type of the Tree.
  * @return A javaslang.collection.Tree Collector.
  */
 static <T> Collector<T, ArrayList<T>, Tree<T>> collector() {
   final Supplier<ArrayList<T>> supplier = ArrayList::new;
   final BiConsumer<ArrayList<T>, T> accumulator = ArrayList::add;
   final BinaryOperator<ArrayList<T>> combiner =
       (left, right) -> {
         left.addAll(right);
         return left;
       };
   final Function<ArrayList<T>, Tree<T>> finisher = Tree::ofAll;
   return Collector.of(supplier, accumulator, combiner, finisher);
 }
コード例 #11
0
 @Test
 public void testAndInt() {
   List<Integer> ints = Arrays.asList(0b1100, 0b0110, 0b101110, 0b11110011);
   Collector<Integer, ?, OptionalInt> collector = MoreCollectors.andingInt(Integer::intValue);
   checkShortCircuitCollector("andInt", OptionalInt.of(0), 4, ints::stream, collector);
   checkCollectorEmpty("andIntEmpty", OptionalInt.empty(), collector);
   assertEquals(
       OptionalInt.of(0),
       IntStreamEx.iterate(16384, i -> i + 1).parallel().boxed().collect(collector));
   assertEquals(
       OptionalInt.of(16384),
       IntStreamEx.iterate(16384, i -> i + 1).parallel().limit(16383).boxed().collect(collector));
   Collector<Integer, ?, Integer> unwrapped =
       MoreCollectors.collectingAndThen(
           MoreCollectors.andingInt(Integer::intValue), OptionalInt::getAsInt);
   assertTrue(unwrapped.characteristics().contains(Characteristics.UNORDERED));
   checkShortCircuitCollector("andIntUnwrapped", 0, 4, ints::stream, unwrapped);
   checkShortCircuitCollector(
       "andIntUnwrapped", 0, 2, Arrays.asList(0x1, 0x10, 0x100)::stream, unwrapped);
 }
コード例 #12
0
ファイル: TreeMap.java プロジェクト: mvh77/javaslang
 /**
  * Returns a {@link java.util.stream.Collector} which may be used in conjunction with {@link
  * java.util.stream.Stream#collect(java.util.stream.Collector)} to obtain a {@link
  * javaslang.collection.TreeMap}.
  *
  * @param <K> The key type
  * @param <V> The value type
  * @return A {@link javaslang.collection.TreeMap} Collector.
  */
 public static <K, V> Collector<Tuple2<K, V>, ArrayList<Tuple2<K, V>>, TreeMap<K, V>> collector() {
   final Supplier<ArrayList<Tuple2<K, V>>> supplier = ArrayList::new;
   final BiConsumer<ArrayList<Tuple2<K, V>>, Tuple2<K, V>> accumulator = ArrayList::add;
   final BinaryOperator<ArrayList<Tuple2<K, V>>> combiner =
       (left, right) -> {
         left.addAll(right);
         return left;
       };
   final Comparator<? super K> comparator = naturalComparator();
   final Function<ArrayList<Tuple2<K, V>>, TreeMap<K, V>> finisher =
       list -> TreeMap.ofEntries(comparator, list);
   return Collector.of(supplier, accumulator, combiner, finisher);
 }
コード例 #13
0
 default <R> R collect(
     Supplier<R> supplier, BiConsumer<R, ? super U> accumulator, BiConsumer<R, R> combiner) {
   return (R)
       this.run(
           (Collector)
               Collector.of(
                   supplier,
                   accumulator,
                   (a, b) -> {
                     combiner.accept(a, b);
                     return a;
                   }));
 }
コード例 #14
0
ファイル: TreeMap.java プロジェクト: enelson/javaslang
 /**
  * Returns a {@link Collector} which may be used in conjunction with {@link
  * java.util.stream.Stream#collect(Collector)} to obtain a {@link TreeMap}.
  *
  * @param <K> The key type
  * @param <V> The value type
  * @param keyComparator A key comparator
  * @return A {@link TreeMap} Collector.
  */
 public static <K, V> Collector<Tuple2<K, V>, ArrayList<Tuple2<K, V>>, TreeMap<K, V>> collector(
     Comparator<? super K> keyComparator) {
   Objects.requireNonNull(keyComparator, "keyComparator is null");
   final Supplier<ArrayList<Tuple2<K, V>>> supplier = ArrayList::new;
   final BiConsumer<ArrayList<Tuple2<K, V>>, Tuple2<K, V>> accumulator = ArrayList::add;
   final BinaryOperator<ArrayList<Tuple2<K, V>>> combiner =
       (left, right) -> {
         left.addAll(right);
         return left;
       };
   final Function<ArrayList<Tuple2<K, V>>, TreeMap<K, V>> finisher =
       list -> ofEntries(keyComparator, list);
   return Collector.of(supplier, accumulator, combiner, finisher);
 }
コード例 #15
0
  /**
   * Trigger a lazy stream and return the results in the Collection created by the collector
   *
   * @param collector Supplier that creates a collection to store results in
   * @return Collection of results
   */
  default <A, R> R run(Collector<U, A, R> collector) {
    if (getLastActive().isSequential()) {
      // if single threaded we can simply push from each Future into the collection to be returned
      if (collector.supplier().get() == null) {
        forEach(r -> {});
        return null;
      }
      A col = collector.supplier().get();
      forEach(r -> collector.accumulator().accept(col, r));
      return collector.finisher().apply(col);
    }

    Function<FastFuture<U>, U> safeJoin =
        (FastFuture<U> cf) -> (U) BlockingStreamHelper.getSafe(cf, getErrorHandler());
    LazyResultConsumer<U> batcher =
        collector.supplier().get() != null
            ? getLazyCollector().get().withResults(new ArrayList<>())
            : new EmptyCollector<>(this.getMaxActive(), safeJoin);

    try {

      this.getLastActive()
          .injectFutures()
          .forEach(
              n -> {
                batcher.accept(n);
              });
    } catch (SimpleReactProcessingException e) {

    }
    if (collector.supplier().get() == null) {
      batcher.block(safeJoin);
      return null;
    }

    return (R)
        batcher
            .getAllResults()
            .stream()
            .map(cf -> BlockingStreamHelper.getSafe(cf, getErrorHandler()))
            .filter(v -> v != MissingValue.MISSING_VALUE)
            .collect((Collector) collector);
  }
コード例 #16
0
ファイル: EventsCommand.java プロジェクト: SampathKondam/onos
 private Collector<JsonNode, ArrayNode, ArrayNode> toArrayNode() {
   return Collector.of(() -> mapper().createArrayNode(), ArrayNode::add, ArrayNode::addAll);
 }
コード例 #17
0
  private static void testCollect() {
    System.out.println();
    System.out.println("Test distinct start");

    // ******** Work with numbers
    Collection<Integer> numbers = Arrays.asList(1, 2, 3, 4);

    // Get sum of all odd numbers
    long sumOdd = numbers.stream().collect(Collectors.summingInt(((p) -> p % 2 == 1 ? p : 0)));
    System.out.println("sumOdd = " + sumOdd); // print  sumEven = 4

    // Subtract 1 to every element and get average
    double average = numbers.stream().collect(Collectors.averagingInt((p) -> p - 1));
    System.out.println("average = " + average); // print  average = 1.5

    // Add 3 to every element and get statisics
    IntSummaryStatistics statistics =
        numbers.stream().collect(Collectors.summarizingInt((p) -> p + 3));
    System.out.println(
        "statistics = "
            + statistics); // print  statistics = IntSummaryStatistics{count=4, sum=22, min=4,
    // average=5.500000, max=7}

    // Get sum all even number using IntSummaryStatistics
    long sumEven =
        numbers.stream().collect(Collectors.summarizingInt((p) -> p % 2 == 0 ? p : 0)).getSum();
    System.out.println("sumEven = " + sumEven); // print  sumEven = 6

    // Split all number to odd and even
    Map<Boolean, List<Integer>> parts =
        numbers.stream().collect(Collectors.partitioningBy((p) -> p % 2 == 0));
    System.out.println("parts = " + parts); // print  parts = {false=[1, 3], true=[2, 4]}

    // ******** Work with strings
    Collection<String> strings = Arrays.asList("a1", "b2", "c3", "a1");

    // Get list of string without duplicate
    List<String> distinct = strings.stream().distinct().collect(Collectors.toList());
    System.out.println("distinct = " + distinct); // print  distinct = [a1, b2, c3]

    // Get array of string without duplicate
    String[] array = strings.stream().distinct().map(String::toUpperCase).toArray(String[]::new);
    System.out.println("array = " + Arrays.asList(array)); // print  array = [A1, B2, C3]

    // Join all element to one string using template:  "<b> v1 : v2 : ... vN </b>"
    String join = strings.stream().collect(Collectors.joining(" : ", "<b> ", " </b>"));
    System.out.println("join = " + join); // print  <b> a1 : b2 : c3 : a1 </b>

    // Transform to map, when first char is key, second char - value
    Map<String, String> map =
        strings
            .stream()
            .distinct()
            .collect(Collectors.toMap((p) -> p.substring(0, 1), (p) -> p.substring(1, 2)));
    System.out.println("map = " + map); // print  map = {a=1, b=2, c=3}

    // Transform to map, with grouping by first char
    Map<String, List<String>> groups =
        strings.stream().collect(Collectors.groupingBy((p) -> p.substring(0, 1)));
    System.out.println("groups = " + groups); // print  groups = {a=[a1, a1], b=[b2], c=[c3]}

    // Transform to map, with grouping by first char and value is join second chars
    Map<String, String> groupJoin =
        strings
            .stream()
            .collect(
                Collectors.groupingBy(
                    (p) -> p.substring(0, 1),
                    Collectors.mapping((p) -> p.substring(1, 2), Collectors.joining(":"))));
    System.out.println(
        "groupJoin = " + groupJoin); // print  groupJoin = groupJoin = {a=1/1, b=2, c=3}

    // Create custom Collector, that join string using StringBuilder
    Collector<String, StringBuilder, String> stringBuilderCollector =
        Collector.of(
            StringBuilder::new, // method accumulator's initialization
            (b, s) -> b.append(s).append(" , "), // method that working with every element
            (b1, b2) -> b1.append(b2).append(" , "), // method that join to accumulator's
            StringBuilder::toString // method that finished working
            );
    String joinBuilder = strings.stream().collect(stringBuilderCollector);
    System.out.println("joinBuilder = " + joinBuilder); // print  joinBuilder = a1 , b2 , c3 , a1 ,

    // Analog Collector using JDK7-
    StringBuilder b = new StringBuilder(); // method accumulator's initialization
    for (String s : strings) {
      b.append(s).append(" , "); // method that working with every element
    }
    String joinBuilderOld = b.toString(); // method that finished working
    System.out.println(
        "joinBuilderOld = " + joinBuilderOld); // print  joinBuilderOld = a1 , b2 , c3 , a1 ,
  }