Java Code Examples for java.util.stream.Collectors#toMap()

The following examples show how to use java.util.stream.Collectors#toMap() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PgClientExamples.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
public void collector01Example(SqlClient client) {

    // Create a collector projecting a row set to a map
    Collector<Row, ?, Map<Long, String>> collector = Collectors.toMap(
      row -> row.getLong("id"),
      row -> row.getString("last_name"));

    // Run the query with the collector
    client.query("SELECT * FROM users")
      .collecting(collector)
      .execute(ar -> {
      if (ar.succeeded()) {
        SqlResult<Map<Long, String>> result = ar.result();

        // Get the map created by the collector
        Map<Long, String> map = result.value();
        System.out.println("Got " + map);
      } else {
        System.out.println("Failure: " + ar.cause().getMessage());
      }
    });
  }
 
Example 2
Source File: MySQLClientExamples.java    From vertx-sql-client with Apache License 2.0 6 votes vote down vote up
public void collector01Example(SqlClient client) {

    // Create a collector projecting a row set to a map
    Collector<Row, ?, Map<Long, String>> collector = Collectors.toMap(
      row -> row.getLong("id"),
      row -> row.getString("last_name"));

    // Run the query with the collector
    client.query("SELECT * FROM users").collecting(collector).execute(ar -> {
        if (ar.succeeded()) {
          SqlResult<Map<Long, String>> result = ar.result();

          // Get the map created by the collector
          Map<Long, String> map = result.value();
          System.out.println("Got " + map);
        } else {
          System.out.println("Failure: " + ar.cause().getMessage());
        }
      });
  }
 
Example 3
Source File: Lambdas.java    From tinkerpop3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This is the missing toMap() method on the Collectors class - specify
 * the key mapper, the value mapper, and the map supplier without having
 * to specify the value merge function.
 * 
 * @param <T> the type of the input elements
 * @param <K> the output type of the key mapping function
 * @param <V> the output type of the value mapping function
 * @param <M> the type of the resulting {@code Map}
 */
public static <T, K, V, M extends Map<K, V>>
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
                         Function<? super T, ? extends V> valueMapper,
                         Supplier<M> mapSupplier) {
    return Collectors.toMap(
            keyMapper, 
            valueMapper,
            (a,b) -> { throw new IllegalStateException(
                                String.format("Duplicate key %s", a)); },
            mapSupplier
            );
}
 
Example 4
Source File: BiCollectors.java    From mug with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a {@link BiCollector} that collects the key-value pairs into an immutable {@link Map}
 * using {@code valueMerger} to merge values of duplicate keys.
 */
public static <K, V> BiCollector<K, V, Map<K, V>> toMap(BinaryOperator<V> valueMerger) {
  requireNonNull(valueMerger);
  return new BiCollector<K, V, Map<K, V>>() {
    @Override
    public <E> Collector<E, ?, Map<K, V>> splitting(
        Function<E, K> toKey, Function<E, V> toValue) {
      return Collectors.toMap(toKey, toValue, valueMerger);
    }
  };
}
 
Example 5
Source File: Lambdas.java    From tinkerpop3 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Collect an Map.Entry stream into a Map using the specified map supplier.
 * 
 * @param <K> the type of key in the incoming entry stream
 * @param <V> the type of value in the incoming entry stream
 * @param <M> the type of the resulting {@code Map}
 */
public static <K, V, M extends Map<K,V>> 
Collector<Entry<K,V>, ?, M> toMap(Supplier<M> mapSupplier) {
    return Collectors.toMap(
            Entry::getKey, 
            Entry::getValue,
            /*
             * We should never need to merge values (assuming the entry 
             * stream has distinct keys).
             */
            (a, b) -> { throw new IllegalStateException(
                                String.format("Duplicate key %s", a)); },
            mapSupplier
            );
}
 
Example 6
Source File: CollectorTestBase.java    From vertx-sql-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testPreparedQuery(TestContext ctx) {
  Collector<Row, ?, Map<Integer, TestingCollectorObject>> collector = Collectors.toMap(
    row -> row.getInteger("id"),
    row -> new TestingCollectorObject(row.getInteger("id"),
      row.getShort("test_int_2"),
      row.getInteger("test_int_4"),
      row.getLong("test_int_8"),
      row.getFloat("test_float"),
      row.getDouble("test_double"),
      row.getString("test_varchar"))
  );

  TestingCollectorObject expected = new TestingCollectorObject(1, (short) 32767, 2147483647, 9223372036854775807L,
    123.456f, 1.234567d, "HELLO,WORLD");

  connector.connect(ctx.asyncAssertSuccess(conn -> {
    conn.preparedQuery("SELECT * FROM collector_test WHERE id = 1")
      .collecting(collector)
      .execute(ctx.asyncAssertSuccess(result -> {
      Map<Integer, TestingCollectorObject> map = result.value();
      TestingCollectorObject actual = map.get(1);
      ctx.assertEquals(expected, actual);
      conn.close();
    }));
  }));
}
 
Example 7
Source File: CollectorsEx.java    From datakernel with Apache License 2.0 4 votes vote down vote up
public static <T, K, V> Collector<T, ?, Map<K, Set<V>>> toMultimap(Function<? super T, ? extends K> keyMapper,
		Function<? super T, ? extends V> valueMapper) {
	return Collectors.toMap(keyMapper, t -> set(valueMapper.apply(t)), CollectionUtils::union);
}
 
Example 8
Source File: MapUtils.java    From bobcat with Apache License 2.0 4 votes vote down vote up
public static <K, U> Collector<Map.Entry<K, U>, ?, Map<K, U>> entriesToMap() {
  return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
 
Example 9
Source File: ScoreTranslator.java    From fix-orchestra with Apache License 2.0 4 votes vote down vote up
private static <K, U> Collector<Map.Entry<K, U>, ?, Map<K, U>> entriesToMap() {
  return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
 
Example 10
Source File: HiveMqtt5SubscriptionHandler.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static <K, V> Collector<Entry<K, V>, ?, Map<K, V>> fromEntries() {
    return Collectors.toMap(Entry::getKey, Entry::getValue);
}
 
Example 11
Source File: MoreCollectors.java    From more-lambdas-java with Artistic License 2.0 4 votes vote down vote up
public static <K, V> Collector<Entry<K, V>, ?, Map<K, V>> toMap() {
    return Collectors.toMap(Entry::getKey, Entry::getValue);
}
 
Example 12
Source File: ConnectivityModelFactory.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static <K, V> Collector<Map.Entry<K, V>, ?, Map<K, V>> fromEntries() {
    return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
 
Example 13
Source File: AbstractWithSwagger.java    From yang2swagger with Eclipse Public License 1.0 4 votes vote down vote up
static <K, U> Collector<Map.Entry<K, U>, ?, Map<K, U>> toMap() {
    return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
 
Example 14
Source File: TestUtils.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
public static <K, U> Collector<Map.Entry<K, U>, ?, Map<K, U>> entriesToMap() {
    return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
 
Example 15
Source File: AuditLogUtil.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static Collector<AuditLogChangeData, ?, Map<String, AuditLogChange<?>>> changeCollector() {
    return Collectors.toMap(
            AuditLogChangeData::key,
            change -> new AuditLogChange<>(change.oldValue().toOptional().orElse(null), change.newValue().toOptional().orElse(null)));
}
 
Example 16
Source File: Configuration.java    From gitflow-incremental-builder with MIT License 4 votes vote down vote up
private static Collector<Entry<String, String>, ?, LinkedHashMap<String, String>> toLinkedMap() {
    return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new);
}
 
Example 17
Source File: SCollectors.java    From Stargraph with MIT License 4 votes vote down vote up
public static <T, K, U> Collector<T, ?, Map<K, U>> toLinkedMap(Function<? super T, ? extends K> keyMapper,
                                                               Function<? super T, ? extends U> valueMapper) {
    return Collectors.toMap(keyMapper, valueMapper, (u, v) -> {
        throw new IllegalStateException(String.format("Duplicate key %s", u));
    }, LinkedHashMap::new);
}
 
Example 18
Source File: StreamUtil.java    From BlogManagePlatform with Apache License 2.0 4 votes vote down vote up
/**
 * 返回collector
 * @author Frodez
 * @date 2019-12-09
 */
public Collector<T, ?, Map<K, V>> hashMap() {
	Assert.notNull(keyMapper, "keyMapper must not be null");
	Assert.notNull(valueMapper, "valueMapper must not be null");
	return Collectors.toMap(keyMapper, valueMapper, mergeFunction(), HashMap::new);
}
 
Example 19
Source File: MoreCollectors.java    From streamex with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that accumulates elements into
 * a result {@code Map} defined by {@code mapSupplier} function
 * whose keys and values are taken from {@code Map.Entry} and combining them
 * using the provided {@code combiner} function to the input elements.
 *
 * <p>If the mapped keys contains duplicates (according to {@link Object#equals(Object)}),
 * the value mapping function is applied to each equal element, and the
 * results are merged using the provided {@code combiner} function.
 *
 * @param <K>         the type of the map keys
 * @param <V>         the type of the map values
 * @param <M>         the type of the resulting {@code Map}
 * @param combiner    a merge function, used to resolve collisions between
 *                    values associated with the same key, as supplied
 *                    to {@link Map#merge(Object, Object, BiFunction)}
 * @param mapSupplier a function which returns a new, empty {@code Map} into
 *                    which the results will be inserted
 * @return {@code Collector} which collects elements into a {@code Map}
 * whose keys and values are taken from {@code Map.Entry} and combining them
 * using the {@code combiner} function
 * @throws NullPointerException if {@code combiner} is null.
 * @throws NullPointerException if {@code mapSupplier} is null.
 * @see #entriesToCustomMap(Supplier)
 * @see Collectors#toMap(Function, Function, BinaryOperator, Supplier)
 * @since 0.7.3
 */
public static <K, V, M extends Map<K, V>> Collector<Entry<? extends K, ? extends V>, ?, M> entriesToCustomMap(
        BinaryOperator<V> combiner, Supplier<M> mapSupplier) {
    Objects.requireNonNull(combiner);
    Objects.requireNonNull(mapSupplier);
    return Collectors.toMap(Entry::getKey, Entry::getValue, combiner, mapSupplier);
}
 
Example 20
Source File: CustomCollectors.java    From vespa with Apache License 2.0 2 votes vote down vote up
/**
 * Returns a {@code Collector} that accumulates elements into a {@code Map}
 * that provides insertion order iteration. This a convenience that can be used
 * instead of calling {@link java.util.stream.Collectors#toMap(Function, Function, BinaryOperator, Supplier)}.
 * with a merger that throws upon duplicate keys.
 *
 * @param keyMapper Mapping function to produce keys.
 * @param valueMapper Mapping function to produce values.
 * @param <T> Type of the input elements.
 * @param <K> Output type of the key mapping function.
 * @param <U> Output type of the value mapping function.
 * @return A collector which collects elements into a map with insertion order iteration.
 * @throws DuplicateKeyException If two elements map to the same key.
 */
public static <T, K, U>
Collector<T, ?, Map<K,U>> toLinkedMap(Function<? super T, ? extends K> keyMapper,
                                      Function<? super T, ? extends U> valueMapper) {
    return Collectors.toMap(keyMapper, valueMapper, throwingMerger(), LinkedHashMap::new);
}