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

x33g5p2x  于2022-01-17 转载在 其他  
字(9.9k)|赞(0)|评价(0)|浏览(175)

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

LinkedHashMap介绍

[英]LinkedHashMap is an implementation of Map that guarantees iteration order. All optional operations are supported.

All elements are permitted as keys or values, including null.

Entries are kept in a doubly-linked list. The iteration order is, by default, the order in which keys were inserted. Reinserting an already-present key doesn't change the order. If the three argument constructor is used, and accessOrder is specified as true, the iteration will be in the order that entries were accessed. The access order is affected by put, get, and putAll operations, but not by operations on the collection views.

Note: the implementation of LinkedHashMap is not synchronized. If one thread of several threads accessing an instance modifies the map structurally, access to the map needs to be synchronized. For insertion-ordered instances a structural modification is an operation that removes or adds an entry. Access-ordered instances also are structurally modified by put, get, and putAll since these methods change the order of the entries. Changes in the value of an entry are not structural changes.

The Iterator created by calling the iterator method may throw a ConcurrentModificationException if the map is structurally changed while an iterator is used to iterate over the elements. Only the remove method that is provided by the iterator allows for removal of elements during iteration. It is not possible to guarantee that this mechanism works in all cases of unsynchronized concurrent modification. It should only be used for debugging purposes.
[中]LinkedHashMap是保证迭代顺序的Map的实现。支持所有可选操作。
所有元素都允许作为键或值,包括null。
条目保存在双链接列表中。默认情况下,迭代顺序是插入关键帧的顺序。重新插入已存在的密钥不会更改顺序。如果使用了三参数构造函数,并且accessOrder指定为true,则迭代将按照条目的访问顺序进行。访问顺序受put、get和putAll操作的影响,但不受集合视图上的操作的影响。
注意:LinkedHashMap的实现不同步。如果访问实例的多个线程中的一个线程在结构上修改了映射,则需要同步对映射的访问。对于插入顺序实例,结构修改是删除或添加条目的操作。由于这些方法改变了条目的顺序,所以访问顺序实例在结构上也被put、get和putAll修改。条目值的更改不是结构更改。
通过调用迭代器方法创建的迭代器可能会抛出ConcurrentModificationException,如果在使用迭代器对元素进行迭代时映射在结构上发生了更改。只有迭代器提供的remove方法允许在迭代期间删除元素。无法保证此机制在所有非同步并发修改的情况下都有效。它只能用于调试目的。

代码示例

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

@Override
public Map<String, String> toSingleValueMap() {
  LinkedHashMap<String, String> singleValueMap = new LinkedHashMap<>(this.headers.size());
  this.headers.forEach((key, value) -> singleValueMap.put(key, value.get(0)));
  return singleValueMap;
}

代码示例来源:origin: apache/kafka

@Override
public V get(K key) {
  return cache.get(key);
}

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

@Override
public Iterable<Entry<K, Collection<V>>> order(List<Entry<K, Collection<V>>> insertionOrder) {
 Map<K, Collection<V>> map = new HashMap<>();
 List<Entry<K, V>> builder = new ArrayList<>();
 for (Entry<K, Collection<V>> entry : insertionOrder) {
  for (V v : entry.getValue()) {
   builder.add(mapEntry(entry.getKey(), v));
  }
  map.put(entry.getKey(), entry.getValue());
 }
 Iterable<Entry<K, V>> ordered = multimapGenerator.order(builder);
 LinkedHashMap<K, Collection<V>> orderedMap = new LinkedHashMap<>();
 for (Entry<K, V> entry : ordered) {
  orderedMap.put(entry.getKey(), map.get(entry.getKey()));
 }
 return orderedMap.entrySet();
}

代码示例来源:origin: apache/kafka

public void moveToEnd(TopicPartition topicPartition) {
  S state = map.remove(topicPartition);
  if (state != null)
    map.put(topicPartition, state);
}

代码示例来源:origin: lipangit/JiaoZiVideoPlayer

public Object getValueFromLinkedMap(int index) {
  int currentIndex = 0;
  for (Object key : urlsMap.keySet()) {
    if (currentIndex == index) {
      return urlsMap.get(key);
    }
    currentIndex++;
  }
  return null;
}

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

@Override
 protected Map<String, String> create(Entry<String, String>[] entries) {
  return populate(new LinkedHashMap<String, String>(), entries);
 }
})

代码示例来源:origin: apache/kafka

private void update(Map<TopicPartition, S> partitionToState) {
  LinkedHashMap<String, List<TopicPartition>> topicToPartitions = new LinkedHashMap<>();
  for (TopicPartition tp : partitionToState.keySet()) {
    List<TopicPartition> partitions = topicToPartitions.computeIfAbsent(tp.topic(), k -> new ArrayList<>());
    partitions.add(tp);
  }
  for (Map.Entry<String, List<TopicPartition>> entry : topicToPartitions.entrySet()) {
    for (TopicPartition tp : entry.getValue()) {
      S state = partitionToState.get(tp);
      map.put(tp, state);
    }
  }
}

代码示例来源:origin: apache/incubator-druid

private void resolveWaitingFutures()
{
 final LinkedHashMap<CustomSettableFuture, Counter> waitingFuturesCopy = new LinkedHashMap<>();
 synchronized (waitingFutures) {
  waitingFuturesCopy.putAll(waitingFutures);
  waitingFutures.clear();
 }
 for (Map.Entry<CustomSettableFuture, Counter> e : waitingFuturesCopy.entrySet()) {
  try {
   e.getKey().set(getRequestsSinceWithoutWait(e.getValue()));
  }
  catch (Exception ex) {
   e.getKey().setException(ex);
  }
 }
}

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

@SuppressWarnings("serial")
public void testLinkedHashMapWithInitialMap() {
 Map<String, String> map =
   new LinkedHashMap<String, String>(
     ImmutableMap.of(
       "Hello", "World",
       "first", "second",
       "polygene", "lubricants",
       "alpha", "betical"));
 LinkedHashMap<String, String> copy = Maps.newLinkedHashMap(map);
 Iterator<Entry<String, String>> iter = copy.entrySet().iterator();
 assertTrue(iter.hasNext());
 Entry<String, String> entry = iter.next();
 assertEquals("Hello", entry.getKey());
 assertEquals("World", entry.getValue());
 assertTrue(iter.hasNext());
 entry = iter.next();
 assertEquals("first", entry.getKey());
 assertEquals("second", entry.getValue());
 assertTrue(iter.hasNext());
 entry = iter.next();
 assertEquals("polygene", entry.getKey());
 assertEquals("lubricants", entry.getValue());
 assertTrue(iter.hasNext());
 entry = iter.next();
 assertEquals("alpha", entry.getKey());
 assertEquals("betical", entry.getValue());
 assertFalse(iter.hasNext());
}

代码示例来源:origin: alibaba/druid

public JdbcSqlStat createSqlStat(String sql) {
  lock.writeLock().lock();
  try {
    JdbcSqlStat sqlStat = sqlStatMap.get(sql);
    if (sqlStat == null) {
      sqlStat = new JdbcSqlStat(sql);
      sqlStat.setDbType(this.dbType);
      sqlStat.setName(this.name);
      sqlStatMap.put(sql, sqlStat);
    }
    return sqlStat;
  } finally {
    lock.writeLock().unlock();
  }
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public V put(K key, V value) {
  lock.lock();
  try {
    return super.put(key, value);
  } finally {
    lock.unlock();
  }
}

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

@VisibleForTesting
static ImmutableMap<File, ClassLoader> getClassPathEntries(ClassLoader classloader) {
 LinkedHashMap<File, ClassLoader> entries = Maps.newLinkedHashMap();
 // Search parent first, since it's the order ClassLoader#loadClass() uses.
 ClassLoader parent = classloader.getParent();
 if (parent != null) {
  entries.putAll(getClassPathEntries(parent));
 }
 for (URL url : getClassLoaderUrls(classloader)) {
  if (url.getProtocol().equals("file")) {
   File file = toFile(url);
   if (!entries.containsKey(file)) {
    entries.put(file, classloader);
   }
  }
 }
 return ImmutableMap.copyOf(entries);
}

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

public void testSegmentPut_evict() {
 int maxSize = 10;
 LocalCache<Object, Object> map =
   makeLocalCache(createCacheBuilder().concurrencyLevel(1).maximumSize(maxSize));
 // manually add elements to avoid eviction
 int originalCount = 1024;
 LinkedHashMap<Object, Object> originalMap = Maps.newLinkedHashMap();
 for (int i = 0; i < originalCount; i++) {
  Object key = new Object();
  Object value = new Object();
  map.put(key, value);
  originalMap.put(key, value);
  if (i >= maxSize) {
   Iterator<Object> it = originalMap.keySet().iterator();
   it.next();
   it.remove();
  }
  assertEquals(originalMap, map);
 }
}

代码示例来源:origin: alibaba/druid

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
  if (list != null && rowIndex < list.size()) {// 没有超出最大行数
    LinkedHashMap<String, Object> dataNow = list.get(rowIndex);
    if (showKeys != null) {
      int titleLen = showKeys.size();
      if (titleLen > 0 && columnIndex < titleLen) {
        return dataNow.get(showKeys.get(columnIndex));
      }
    } else {
      Object[] values = dataNow.values().toArray();
      if (columnIndex < values.length) {
        return values[columnIndex];
      }
    }
  }
  return null;
}

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

@Override
public Set<Entry<String, V>> entrySet() {
  return this.targetMap.entrySet();
}

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

@Override
public Set<String> keySet() {
  return this.targetMap.keySet();
}

代码示例来源:origin: apache/kafka

private void checkState(PartitionStates<String> states, LinkedHashMap<TopicPartition, String> expected) {
  assertEquals(expected.keySet(), states.partitionSet());
  assertEquals(expected.size(), states.size());
  List<PartitionStates.PartitionState<String>> statesList = new ArrayList<>();
  for (Map.Entry<TopicPartition, String> entry : expected.entrySet()) {
    statesList.add(new PartitionStates.PartitionState<>(entry.getKey(), entry.getValue()));
    assertTrue(states.contains(entry.getKey()));
  }
  assertEquals(statesList, states.partitionStates());
}

代码示例来源:origin: alibaba/druid

public List<JdbcSqlStatValue> getRuningSqlList() {
  List<JdbcSqlStat> stats = new ArrayList<JdbcSqlStat>(sqlStatMap.size());
  lock.readLock().lock();
  try {
    for (Map.Entry<String, JdbcSqlStat> entry : sqlStatMap.entrySet()) {
      JdbcSqlStat stat = entry.getValue();
      if (stat.getRunningCount() >= 0) {
        stats.add(entry.getValue());
      }
    }
  } finally {
    lock.readLock().unlock();
  }
  List<JdbcSqlStatValue> values = new ArrayList<JdbcSqlStatValue>(stats.size());
  for (JdbcSqlStat stat : stats) {
    JdbcSqlStatValue value = stat.getValue(false);
    if (value.getRunningCount() > 0) {
      values.add(value);
    }
  }
  return values;
}

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

@Override
@Nullable
public V computeIfAbsent(String key, Function<? super String, ? extends V> mappingFunction) {
  String oldKey = this.caseInsensitiveKeys.putIfAbsent(convertKey(key), key);
  if (oldKey != null) {
    return this.targetMap.get(oldKey);
  }
  return this.targetMap.computeIfAbsent(key, mappingFunction);
}

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

@Override
@Nullable
public V putIfAbsent(String key, @Nullable V value) {
  String oldKey = this.caseInsensitiveKeys.putIfAbsent(convertKey(key), key);
  if (oldKey != null) {
    return this.targetMap.get(oldKey);
  }
  return this.targetMap.putIfAbsent(key, value);
}

相关文章