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

The following examples show how to use java.util.stream.Collectors#toMap() . These examples are extracted from open source projects. 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
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
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 Project: mug   File: BiCollectors.java    License: 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 4
@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 5
Source Project: tinkerpop3   File: Lambdas.java    License: 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 Project: tinkerpop3   File: Lambdas.java    License: 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 7
Source Project: BlogManagePlatform   File: StreamUtil.java    License: 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 8
Source Project: datakernel   File: CollectorsEx.java    License: 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 9
Source Project: Stargraph   File: SCollectors.java    License: 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 10
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 11
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 12
public static <K, U> Collector<Map.Entry<K, U>, ?, Map<K, U>> entriesToMap() {
    return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
 
Example 13
static <K, U> Collector<Map.Entry<K, U>, ?, Map<K, U>> toMap() {
    return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
 
Example 14
private static <K, V> Collector<Map.Entry<K, V>, ?, Map<K, V>> fromEntries() {
    return Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue);
}
 
Example 15
public static <K, V> Collector<Entry<K, V>, ?, Map<K, V>> toMap() {
    return Collectors.toMap(Entry::getKey, Entry::getValue);
}
 
Example 16
private static <K, V> Collector<Entry<K, V>, ?, Map<K, V>> fromEntries() {
    return Collectors.toMap(Entry::getKey, Entry::getValue);
}
 
Example 17
Source Project: fix-orchestra   File: ScoreTranslator.java    License: 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 18
Source Project: bobcat   File: MapUtils.java    License: 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 19
Source Project: streamex   File: MoreCollectors.java    License: 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 Project: vespa   File: CustomCollectors.java    License: 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);
}