java.util.Map类的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(7.1k)|赞(0)|评价(0)|浏览(172)

本文整理了Java中java.util.Map类的一些代码示例,展示了Map类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Map类的具体详情如下:
包路径:java.util.Map
类名称:Map

Map介绍

[英]A Map is a data structure consisting of a set of keys and values in which each key is mapped to a single value. The class of the objects used as keys is declared when the Map is declared, as is the class of the corresponding values.

A Map provides helper methods to iterate through all of the keys contained in it, as well as various methods to access and update the key/value pairs.
[中]映射是由一组键和值组成的数据结构,其中每个键映射到一个值。在声明映射时,将声明用作键的对象的类,以及相应值的类。
映射提供了助手方法来遍历其中包含的所有键,以及各种方法来访问和更新键/值对。

代码示例

canonical example by Tabnine

private void mappingWordsLength(List<String> wordsList) {
 Map<Integer, Set<String>> mapping = new HashMap<>();
 for (String word : wordsList) {
  mapping.computeIfAbsent(word.length(), HashSet::new).add(word);
 }
 List<Integer> lengths = new LinkedList<>(mapping.keySet());
 Collections.sort(lengths);
 lengths.forEach(n -> System.out.println(mapping.get(n).size() + " words with " + n + " chars"));
}

代码示例来源:origin: square/retrofit

ServiceMethod<?> loadServiceMethod(Method method) {
 ServiceMethod<?> result = serviceMethodCache.get(method);
 if (result != null) return result;
 synchronized (serviceMethodCache) {
  result = serviceMethodCache.get(method);
  if (result == null) {
   result = ServiceMethod.parseAnnotations(this, method);
   serviceMethodCache.put(method, result);
  }
 }
 return result;
}

代码示例来源:origin: google/guava

/** An implementation of {@link Map#putAll}. */
static <K, V> void putAllImpl(Map<K, V> self, Map<? extends K, ? extends V> map) {
 for (Entry<? extends K, ? extends V> entry : map.entrySet()) {
  self.put(entry.getKey(), entry.getValue());
 }
}

代码示例来源:origin: spring-projects/spring-framework

private void updateBindingContext(BindingContext context, ServerWebExchange exchange) {
  Map<String, Object> model = context.getModel().asMap();
  model.keySet().stream()
      .filter(name -> isBindingCandidate(name, model.get(name)))
      .filter(name -> !model.containsKey(BindingResult.MODEL_KEY_PREFIX + name))
      .forEach(name -> {
        WebExchangeDataBinder binder = context.createDataBinder(exchange, model.get(name), name);
        model.put(BindingResult.MODEL_KEY_PREFIX + name, binder.getBindingResult());
      });
}

代码示例来源:origin: google/guava

@Override
public int size() {
 int size = 0;
 for (Map<C, V> map : backingMap.values()) {
  size += map.size();
 }
 return size;
}

代码示例来源:origin: square/okhttp

@Override public void rename(File from, File to) throws IOException {
 Buffer buffer = files.remove(from);
 if (buffer == null) throw new FileNotFoundException();
 files.put(to, buffer);
}

代码示例来源:origin: square/okhttp

private static Map<ByteString, Integer> nameToFirstIndex() {
 Map<ByteString, Integer> result = new LinkedHashMap<>(STATIC_HEADER_TABLE.length);
 for (int i = 0; i < STATIC_HEADER_TABLE.length; i++) {
  if (!result.containsKey(STATIC_HEADER_TABLE[i].name)) {
   result.put(STATIC_HEADER_TABLE[i].name, i);
  }
 }
 return Collections.unmodifiableMap(result);
}

代码示例来源:origin: ReactiveX/RxJava

static void tryPutIntoPool(boolean purgeEnabled, ScheduledExecutorService exec) {
  if (purgeEnabled && exec instanceof ScheduledThreadPoolExecutor) {
    ScheduledThreadPoolExecutor e = (ScheduledThreadPoolExecutor) exec;
    POOLS.put(e, exec);
  }
}

代码示例来源:origin: google/guava

final void assertNonNullValues(Object... expectedValues) {
 assertEquals(expectedValues.length, arguments.size());
 for (int i = 0; i < expectedValues.length; i++) {
  assertEquals("Default value for parameter #" + i, expectedValues[i], arguments.get(i));
 }
}

代码示例来源:origin: google/guava

@SuppressWarnings("unchecked")
@Override
public void removePredecessor(N node) {
 Object previousValue = adjacentNodeValues.get(node);
 if (previousValue == PRED) {
  adjacentNodeValues.remove(node);
  checkNonNegative(--predecessorCount);
 } else if (previousValue instanceof PredAndSucc) {
  adjacentNodeValues.put((N) node, ((PredAndSucc) previousValue).successorValue);
  checkNonNegative(--predecessorCount);
 }
}

代码示例来源:origin: google/guava

private static void insertIntoReplica(Map<Integer, AtomicInteger> replica, int newValue) {
 if (replica.containsKey(newValue)) {
  replica.get(newValue).incrementAndGet();
 } else {
  replica.put(newValue, new AtomicInteger(1));
 }
}

代码示例来源:origin: google/guava

@GwtIncompatible // SerializableTester
public void testViewSerialization() {
 Map<String, Integer> map = ImmutableMap.of("one", 1, "two", 2, "three", 3);
 LenientSerializableTester.reserializeAndAssertLenient(map.entrySet());
 LenientSerializableTester.reserializeAndAssertLenient(map.keySet());
 Collection<Integer> reserializedValues = reserialize(map.values());
 assertEquals(Lists.newArrayList(map.values()), Lists.newArrayList(reserializedValues));
 assertTrue(reserializedValues instanceof ImmutableCollection);
}

代码示例来源:origin: google/guava

@Override
public V apply(@Nullable K key) {
 V result = map.get(key);
 return (result != null || map.containsKey(key)) ? result : defaultValue;
}

代码示例来源:origin: google/guava

private void assertMapSize(Map<?, ?> map, int size) {
 assertEquals(size, map.size());
 if (size > 0) {
  assertFalse(map.isEmpty());
 } else {
  assertTrue(map.isEmpty());
 }
 assertCollectionSize(map.keySet(), size);
 assertCollectionSize(map.entrySet(), size);
 assertCollectionSize(map.values(), size);
}

代码示例来源:origin: spring-projects/spring-framework

@Override
  protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
      HttpServletResponse response) throws Exception {
    for (String key : attrsToValidate.keySet()) {
      assertTrue("Model should contain attribute named " + key, model.containsKey(key));
      assertEquals(attrsToValidate.get(key), model.get(key));
      validatedAttrCount++;
    }
  }
};

代码示例来源:origin: iluwatar/java-design-patterns

@Override
public Optional<Customer> getById(final int id) {
 return Optional.ofNullable(idToCustomer.get(id));
}

代码示例来源:origin: google/guava

public void testRowKeyMapHeadMap() {
 sortedTable = create("foo", 1, 'a', "bar", 1, 'b', "foo", 3, 'c');
 Map<String, Map<Integer, Character>> map = sortedTable.rowMap().headMap("cat");
 assertEquals(1, map.size());
 assertEquals(ImmutableMap.of(1, 'b'), map.get("bar"));
 map.clear();
 assertTrue(map.isEmpty());
 assertEquals(Collections.singleton("foo"), sortedTable.rowKeySet());
}

代码示例来源:origin: google/guava

private static long worstCaseQueryOperations(Map<?, ?> map, CallsCounter counter) {
  long worstCalls = 0;
  for (Object k : map.keySet()) {
   counter.zero();
   Object unused = map.get(k);
   worstCalls = Math.max(worstCalls, counter.total());
  }
  return worstCalls;
 }
}

代码示例来源:origin: google/guava

@MapFeature.Require(SUPPORTS_REMOVE)
public void testClear() {
 getMap().clear();
 assertTrue("After clear(), a map should be empty.", getMap().isEmpty());
 assertEquals(0, getMap().size());
 assertFalse(getMap().entrySet().iterator().hasNext());
}

代码示例来源:origin: google/guava

public void testAsMap() {
 Set<String> strings = ImmutableSet.of("one", "two", "three");
 Map<String, Integer> map = Maps.asMap(strings, LENGTH_FUNCTION);
 assertEquals(ImmutableMap.of("one", 3, "two", 3, "three", 5), map);
 assertEquals(Integer.valueOf(5), map.get("three"));
 assertNull(map.get("five"));
 assertThat(map.entrySet())
   .containsExactly(mapEntry("one", 3), mapEntry("two", 3), mapEntry("three", 5))
   .inOrder();
}

相关文章