[Java] compulsory acquisition of four methods in the Map key Key by Value

1 Introduction

We all know Mapthat the key is stored on the <Key,Value>vessel, knowing Key value, use Map.get(key)can quickly get Value value. However, sometimes we need to turn gets to know the value of Value, find the Key value.

This article describes four methods by example, by passing Value is acquired to obtain a Key value.

2 four methods

2.1 round-robin

Circulation method is by traversing the Map of Entry, a comparison, to meet the conditions to find out. There will be three cases:

  • (1) find a value

  • (2) a plurality of values ​​found

  • (3) can not be found

Specific code as follows:

@Test
public void loop() {
  Map<String, Integer> map = ImmutableMap.of("A", 1, "B", 2, "C", 3, "D", 2);
  //找到一个值
  assertEquals("A", getKeyByLoop(map, 1));
  //找到多个值
  assertEquals(ImmutableSet.of("B", "D"), getKeysByLoop(map, 2));
  //找不到
  assertEquals(null, getKeyByLoop(map, 4));
}

private <K, V> K getKeyByLoop(Map<K, V> map, V value) {
  for (Map.Entry<K, V> entry : map.entrySet()) {
    if (Objects.equals(entry.getValue(), value)) {
      return entry.getKey();
    }
  }
  return null;
}

private <K, V> Set<K> getKeysByLoop(Map<K, V> map, V value) {
  Set<K> set = Sets.newHashSet();
  for (Map.Entry<K, V> entry : map.entrySet()) {
    if (Objects.equals(entry.getValue(), value)) {
      set.add(entry.getKey());
    }
  }
  return set;
}

Would like to say is that in contrast to equality, when using a Objects.equals(a, b)method rather than a.equals(b)the method. This avoids null pointer exception.

2.2 Stream method

StreamAlways elegant and intuitive approach can provide in a variety of set operations, easy to write and easy to understand. Through a filter, equal to the value that satisfies the condition taken out, as follows:

@Test
public void stream() {
  Map<String, Integer> map = ImmutableMap.of("A", 1, "B", 2, "C", 3, "D", 2);
  assertEquals(ImmutableSet.of("B", "D"), getKeysByStream(map, 2));
}

private <K, V> Set<K> getKeysByStream(Map<K, V> map, V value) {
  return map.entrySet()
    .stream()
    .filter(kvEntry -> Objects.equals(kvEntry.getValue(), value))
    .map(Map.Entry::getKey)
    .collect(Collectors.toSet());
}

2.3 Guava的BiMap

Google is Guavaproviding BiMapsuch a two-way Map, calls the inverse()method returns a reverse association BiMap, then they can get()get key value method.

code show as below:

@Test
public void guava() {
  BiMap<String, Integer> biMap = HashBiMap.create();
  biMap.put("A", 1);
  biMap.put("B", 2);
  biMap.put("C", null);
  biMap.put("D", 4);
  assertEquals("D", biMap.inverse().get(4));
}

Note that, BiMapas a two-way Map, it can not store many to one relationship; and HashMapit is possible. In fact well understood, because it is bi-directional, that is, to meet the Keyunique values, but also to meet the Valueuniqueness of the value. If stored inside the same Value, will throw an exception: java.lang.IllegalArgumentException: value already present.

2.4 Apache Commons Collections的BidiMap

Similarly, Apache Commons Collectionsalso provides a two-way Map of the class BidiMap, it is also to maintain the one-to-many-can not. It provides a getKey(value)method to return Key value. code show as below:

@Test
public void apacheCommons() {
  BidiMap<String, Integer> bidiMap = new DualHashBidiMap<>();
  bidiMap.put("A", 1);
  bidiMap.put("B", 2);
  bidiMap.put("C", null);
  bidiMap.put("D", 4);
  assertEquals("D", bidiMap.getKey(4));
}

And Guava's BiMapdifferent is that when storing the same Value, it will not throw an exception, but overwrite the original data.

3 summary

This article describes four methods of obtaining the value of the Map Key Value by values, respectively, is a cyclic method, Stream, Guava, Apache Commons Collections, four methods similar but not the same.

  • (1) and the circulation method is used to traverse the nature Stram, if the reverse is often necessary to take a Map Key value is not recommended to use, and may be considered the Guava bidirectional Map Apache Commons provided;

  • (2) Map is actually a two-way space for time thinking, although you can find Key value to meet the conditions of the rapid, but it also uses more space to store two-way Map;

  • (3) does not support the two-way relationship between the many-to-Map.

How to choose, to choose depends on the specific needs of the.


Welcome to public concern number < pumpkin slow, said >, you will continue to update ...

More books, more sharing; and more writing, more than finishing.

Guess you like

Origin www.cnblogs.com/larrydpk/p/11786001.html