Java map поиск значений

get string value from HashMap depending on key name

I have a HashMap with various keys and values, how can I get one value out? I have a key in the map called my_code , it should contain a string, how can I just get that without having to iterate through the map? So far I’ve got..

 HashMap newMap = new HashMap(paramMap); String s = newMap.get("my_code").toString(); 

I’m expecting to see a String , such as «ABC» or «DEF» as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454 Sorry, I’m not too familiar with maps as you can probably guess 😉

10 Answers 10

Object value = map.get(myCode); 

Edit: you edited your question with the following:

I’m expecting to see a String, such as «ABC» or «DEF» as that is what I put in there initially, but if I do a System.out.println() I get something like java.lang.string#F0454

Sorry, I’m not too familiar with maps as you can probably guess 😉

You’re seeing the outcome of Object#toString() . But the java.lang.String should already have one implemented, unless you created a custom implementation with a lowercase s in the name: java.lang.string . If it is actually a custom object, then you need to override Object#toString() to get a «human readable string» whenever you do a System.out.println() or toString() on the desired object. For example:

@Override public String toString()

Источник

Interface Map

An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.

The Map interface provides three collection views, which allow a map’s contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map’s collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

All general-purpose map implementation classes should provide two «standard» constructors: a void (no arguments) constructor which creates an empty map, and a constructor with a single argument of type Map , which creates a new map with the same key-value mappings as its argument. In effect, the latter constructor allows the user to copy any map, producing an equivalent map of the desired class. There is no way to enforce this recommendation (as interfaces cannot contain constructors) but all of the general-purpose map implementations in the JDK comply.

The «destructive» methods contained in this interface, that is, the methods that modify the map on which they operate, are specified to throw UnsupportedOperationException if this map does not support the operation. If this is the case, these methods may, but are not required to, throw an UnsupportedOperationException if the invocation would have no effect on the map. For example, invoking the putAll(Map) method on an unmodifiable map may, but is not required to, throw the exception if the map whose mappings are to be «superimposed» is empty.

Some map implementations have restrictions on the keys and values they may contain. For example, some implementations prohibit null keys and values, and some have restrictions on the types of their keys. Attempting to insert an ineligible key or value throws an unchecked exception, typically NullPointerException or ClassCastException . Attempting to query the presence of an ineligible key or value may throw an exception, or it may simply return false; some implementations will exhibit the former behavior and some will exhibit the latter. More generally, attempting an operation on an ineligible key or value whose completion would not result in the insertion of an ineligible element into the map may throw an exception or it may succeed, at the option of the implementation. Such exceptions are marked as «optional» in the specification for this interface.

Many methods in Collections Framework interfaces are defined in terms of the equals method. For example, the specification for the containsKey(Object key) method says: «returns true if and only if this map contains a mapping for a key k such that (key==null ? k==null : key.equals(k)) .» This specification should not be construed to imply that invoking Map.containsKey with a non-null argument key will cause key.equals(k) to be invoked for any key k . Implementations are free to implement optimizations whereby the equals invocation is avoided, for example, by first comparing the hash codes of the two keys. (The Object.hashCode() specification guarantees that two objects with unequal hash codes cannot be equal.) More generally, implementations of the various Collections Framework interfaces are free to take advantage of the specified behavior of underlying Object methods wherever the implementor deems it appropriate.

Some map operations which perform recursive traversal of the map may fail with an exception for self-referential instances where the map directly or indirectly contains itself. This includes the clone() , equals() , hashCode() and toString() methods. Implementations may optionally handle the self-referential scenario, however most current implementations do not do so.

Unmodifiable Maps

  • They are unmodifiable. Keys and values cannot be added, removed, or updated. Calling any mutator method on the Map will always cause UnsupportedOperationException to be thrown. However, if the contained keys or values are themselves mutable, this may cause the Map to behave inconsistently or its contents to appear to change.
  • They disallow null keys and values. Attempts to create them with null keys or values result in NullPointerException .
  • They are serializable if all keys and values are serializable.
  • They reject duplicate keys at creation time. Duplicate keys passed to a static factory method result in IllegalArgumentException .
  • The iteration order of mappings is unspecified and is subject to change.
  • They are value-based. Programmers should treat instances that are equal as interchangeable and should not use them for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail. Callers should make no assumptions about the identity of the returned instances. Factories are free to create new instances or reuse existing ones.
  • They are serialized as specified on the Serialized Form page.

This interface is a member of the Java Collections Framework.

Источник

Searching for a Value in a HashMap

Now, if I want to search for «Barry» in the HashMap and get the key which is the most recent (in this case Dec 26th), how would I go about doing that? The .values() method doesn’t seem to work as each key has an ArrayList instead of just one element.

I am fairly new to Java. So, i am not exactly sure how to use an iterator here for this. Can you give me some pointers on that?

3 Answers 3

In java 8 you could use something like this:

Optional>> first = map .entrySet() .stream() .filter(entry -> entry.getValue().contains("Barry")) .sorted(Map.Entry.comparingByKey()) .findFirst(); 

This get all the entries from the map, filters them based on the value, sort them based on keys and get the first one, if any. You can then use first.ifPresent() method to do whatever you want with the first entry, here i just printing them to the console:

Maybe this is NOT the most efficient algorithm but sure it works

Update 1: To sort dates from latest to earliest, use this:

sorted(Map.Entry.>comparingByKey().reversed()) 

Update 2: As Andreas said, you can use max instead of sorted which has better asymptotic behavior. In fact, since you just want the latest item, there is no need for sorting entries in order to get it:

Optional>> found = map .entrySet() .stream() .filter(entry -> entry.getValue().contains("Barry")) .max(Map.Entry.comparingByKey()); 

A Map can be seen as a Set> . The code streams that set, picking all entries with value «Barry» (that’s the filter call with the lambda function). Then it asks the results to be sorted according to the natural ordering of Map.Entry, and picks the first every according to that ordering. I don’t think this pipeline would work since Map.Entry does not implement Comparable. You might want to use .sorted(Map.Entry.comparingByKey()) instead.

Wouldn’t max(comparator) perform much better than sorted(comparator).findFirst() ? Fewer comparisons: n — 1 vs. n * log(n) (probably).

Use the map’s Entry Set . For example:

HashMap> map = new HashMap>(); ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(); list1.add("One"); list1.add("Two"); list1.add("Three"); list2.add("Cat"); list2.add("Dog"); list2.add("Fish"); map.put("Numbers", list1); map.put("Animals", list2); for(Map.Entry> entry : map.entrySet())

Output: Found Cat in Animals

Essentially, what we are doing is iterating over the map’s Entry Set , checking if each value (which we specified is an ArrayList ) contains the String we are looking for, and if it does, we print out the key of the current Entry . (Which, in your case, would be your LocalDate .)

Since you want to find the key while searching for a value, you need to use entrySet() .

Given that your keys are dates, and hence have a natural order, and you want latest matching date, you have 3 choices:

  • Keep the HashMap , search entire list, and remember largest key value.
  • Change to TreeMap , search backwards using descendingMap() , and stop on first hit.
  • Change to reverse-order TreeMap , search, and stop on first hit.

If your list is huge and/or you do the search a lot, a TreeMap is preferable, for performance reasons.

Since it is unclear whether LocalDate is from Java 8 or from Joda-Time, the following code uses compareTo , which is implemented by both. Code doesn’t use Java 8 specific features.

// HashMap HashMap> map = new HashMap<>(); . LocalDate matchedKey = null; for (Entry> entry : map.entrySet()) if (entry.getValue().contains(valueToFind)) if (matchedKey == null || entry.getKey().compareTo(matchedKey) > 0) matchedKey = entry.getKey(); 
// TreeMap (descending search) TreeMap> map = new TreeMap<>(); . LocalDate matchedKey = null; for (Entry> entry : map.descendingMap().entrySet()) if (entry.getValue().contains(valueToFind))
// TreeMap (reverse-order) TreeMap> map = new TreeMap<>(Collections.reverseOrder()); // or Comparator.reverseOrder() in Java 8 . LocalDate matchedKey = null; for (Entry> entry : map.entrySet()) if (entry.getValue().contains(valueToFind))

Of course, in Java 8, these can also be done using streams and Lambdas.

Источник

Читайте также:  Http karataev nm ru solvers index html
Оцените статью