Tabnine Logo
Map
Code IndexAdd Tabnine to your IDE (free)

How to use
Map
in
java.util

Best Java code snippets using java.util.Map (Showing top 20 results out of 446,355)

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();
}
java.utilMap

Javadoc

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.

Most used methods

  • put
    Maps the specified key to the specified value.
  • get
  • entrySet
    Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes t
  • containsKey
    Returns whether this Map contains the specified key.
  • keySet
    Returns a set of the keys contained in this Map. The Set is backed by this Map so changes to one are
  • values
    Returns a Collection view of the values contained in this map. The collection is backed by the map,
  • remove
  • size
    Returns the number of mappings in this Map.
  • isEmpty
    Returns true if this map contains no key-value mappings.
  • clear
    Removes all elements from this Map, leaving it empty.
  • putAll
    Copies all of the mappings from the specified map to this map (optional operation). The effect of th
  • forEach
  • putAll,
  • forEach,
  • equals,
  • computeIfAbsent,
  • hashCode,
  • getOrDefault,
  • containsValue,
  • putIfAbsent,
  • compute,
  • merge

Popular in Java

  • Reading from database using SQL prepared statement
  • requestLocationUpdates (LocationManager)
  • getSystemService (Context)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • BorderLayout (java.awt)
    A border layout lays out a container, arranging and resizing its components to fit in five regions:
  • SocketTimeoutException (java.net)
    This exception is thrown when a timeout expired on a socket read or accept operation.
  • Time (java.sql)
    Java representation of an SQL TIME value. Provides utilities to format and parse the time's represen
  • LinkedHashMap (java.util)
    LinkedHashMap is an implementation of Map that guarantees iteration order. All optional operations a
  • ConcurrentHashMap (java.util.concurrent)
    A plug-in replacement for JDK1.5 java.util.concurrent.ConcurrentHashMap. This version is based on or
  • Executors (java.util.concurrent)
    Factory and utility methods for Executor, ExecutorService, ScheduledExecutorService, ThreadFactory,
  • Github Copilot alternatives
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now