Java map contains all

Class HashMap

Type Parameters: K — the type of keys maintained by this map V — the type of mapped values All Implemented Interfaces: Serializable , Cloneable , Map Direct Known Subclasses: LinkedHashMap , PrinterStateReasons

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable , except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

This implementation provides constant-time performance for the basic operations ( get and put ), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the «capacity» of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it’s very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put ). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table. Note that using many keys with the same hashCode() is a sure way to slow down performance of any hash table. To ameliorate impact, when keys are Comparable , this class may use comparison order among keys to help break ties.

Читайте также:  Как лучше изучить css

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be «wrapped» using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(. ));

The iterators returned by all of this class’s «collection view methods» are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException . Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Источник

Java java check if map contains all keys

If you are doing this sort of comparison a lot and you cannot map from element to key then it may be worth keeping a HashSet of the values for this purpose. Of course, this would be inefficient for large maps.

Читайте также:  Python sqlite3 delete all

Verify that all key/value pairs in a Map are present in another Map

Use Map.equals(Map other) to check if both maps contain the same mappings. If you just need to check if a map is a subset of another map, use map.entrySet().containsAll(other.entrySet()) .

Is there an efficient way of checking if HashMap contains keys that, You can check whether a map contains a value already by calling map.values().contains(value)

How to check whether a HashMap has all the elements of an ArrayList?

Map map = new HashMap(); List list = new ArrayList(); 

The approach you tried (well, nearly, as pointed out by Marko Topolnik) is indeed correct:

if (map.values().containsAll(list))

(Or map.keySet().containsAll(list) if you were interested in the map keys instead of values .)

For this to work as expected for custom types, you of course must have implemented equals() and hashcode() correctly for them. (See e.g. this question or better yet, read Item 9 in Effective Java .)

By the way, when working with Java Collections, it is good practice to define fields and variables using the interfaces (such as List, Set, Map), not implementation types (e.g. ArrayList, HashSet, HashMap). For example:

List list = new ArrayList(); Map map = new HashMap(); 

Similarly, a more «correct» or fluent title for your question would have been «How to check whether a Map has all the elements of a List ?». Check out the Java Collections tutorial for more info.

Your code is correct except..

[EDIT] You can use HashMap.containsValue(Object value)

public boolean containsList(HashMap map, List list) < for(V value : list) < if(!map.containsValue(value)) < return false; >> return true; > 

Your code should work — but will not be particularly efficient. You need to compare every element in the list with every element in the map.

If (and only if) you can easily extract the key of the map from the elements then you would be better off looping through your List and for each element do map.containsKey(getKey(elem)) , this will be much faster.

If you are doing this sort of comparison a lot and you cannot map from element to key then it may be worth keeping a HashSet of the values for this purpose.

Check if a Map Value contains a particular String and an element, map.forEach((key, value) -> < if (Arrays.stream(value.toString().split(";"))

How to check if all Keys of the given Map are present in a one of the Maps contained within a List<Map<String, Object>> in Java efficiently?

But I don’t know if there is a more efficient way to do the same thing?

In order to find out whether a single map in a list matches the given criteria you don’t need to check every element, instead you need to find the first match and break the iteration.

Читайте также:  Cron выполнить php скрипт

To achieve that in place of forEach and AtomicBoolean , which act much slower than a simple boolean flag, you can use a plain for loop with a break statement inside it.

Or you can make use of the Java 8 streams with anyMatch() as terminal operation. anyMatch() — is a so-called short circuit operation, it’ll break when the first element matching the given predicate will be found.

return contentList.stream() .anyMatch(map -> map.navigableKeySet().containsAll(expectedMap.navigableKeySet())); 

How to make this method case-insensitive for «expectedMap» keys?

It’s not possible to achieve using hash-based collections.

But you can utilize in place of the Map the NavigableMap interface, and it’s implementation TreeMap by providing a case-insensitive Comparator . And there’s a predefined case-insensitive comparator strings provided by the String class as its static field.

List> contentList = new ArrayList<>(); NavigableMap objectMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); . 

Note, that maintaining an ordered collection has a cost. Contrary to HashMap which allows to add and retrieve entries in constant time O(1) , methods like get() , put() , containsKey() will perform in O(log n) with TreeMap .

You can play around with this Online Demo

In order to compare keys in case-insensitive manner, a simple solution would be to generate a string of each map and then simply compare strings. Of course, this would be inefficient for large maps.

// A simple method to concatenate entries of map as key=value pairs (in sorted key order) private static String toKVString(Map map, String delimiter) < return map.entrySet().stream() .sorted(Comparator.comparing(Map.Entry::getKey)) .map(e ->String.format("%s=%s", e.getKey().toLowerCase(), e.getValue())) .collect(Collectors.joining(delimiter)); > 

Then, we can use simple string equality:

final String delim = "/"; // choose something not found in keys or values final String expectedMapAsString = toKVString(expectedMap, delim); boolean found = contentList.stream() .anyMatch(map -> expectedMapAsString.equals(toKVString(map, delim))); 

Way to find if map contains any keys NOT from a list, Instead of using ! on the list, why don’t you try .. boolean allKeysInList = map.entrySet() .stream() .allMatch(entry -> list.contains(entry

Check if each map of the list contains all key-values combination from two sources via Stream api

I just learned this.. How to flat map of values to another map grouped by key

 List> expectedList = documents .stream() .flatMap(d -> persons.stream().map(p -> Map.of("id", d, "lastName", p))) .collect(toList()); 

What is the optimal way to check if a map contains any empty values, Your map stores key/value pairs where either key or value is the question and the other one is the answer. What you demand is there must not

Источник

Оцените статью