Java Google guava multimap: Get all the list entrys - java

I am using a multimap like this
Multimap<String, MyObject> tasksMap = ArrayListMultimap.create();
Where there can be multiple items for the same key, get the List value for every key in the map?

.asMap() lets you get a map and you can then iterate over its .entrySet().
Something like
for (Entry<String, Collection<MyObject>> e : tasksMap.asMap().entrySet()) {
String key = e.getKey();
Collection<MyObject> values = e.getValue();
...
}

Just use get method to get all values for a key
List<MyObject> values = tasksMap.get(key);
or use values to get all values for every key in map
Collection<List<MyObject>> values = tasksMap.values();
or entries to get all entries
Collection<Map.Entry<String, List<MyObject>>> entries = tasksMap.entries()

Related

Iterating over a List<Tuple> inside hashmap in java

I have stored a key-value pair in the hash map where key is a string ID and value is List of tuple .I need to fetch the data present in the list and insert into Database. What is the code logic to iterate over the List of tuple inside a map and get the data from the list?
One of the ways is using Java 8 streams
map.values() // get all the list of tuples i.e. values
.stream() // java 8 stream api
.flatMap(listOfTuple -> listOfTuple.stream()) // flattening the list
.forEach(tuple -> doWhatEverWithTuple(tuple)); // use individual tuple
You can get the values from map using map.values method or you can use Entry if you need to add some conditions based on keys.
Map<String, List<Tuple>> data = somemethod();
for(List<Tuple> tuples : data.values()) {
//... some code
}
or
for(Map.Entry<String, List<Tuple>> entry : data.entrySet()) {
String key = entry.getKey();
List<Tuple> tuples = entry.getValue();
// ... Some code
}

How to add List element to map by key?

I use the following approach for sorting items by key:
final Map<Integer, UUID> map = new TreeMap<>();
while (rowIterator.hasNext()) {
// Add Items to the TreeMap
mapppp.put(1, UUID.fromString("610e9040-840c-48c5-aa64-f193ed896133"));
mapppp.put(2, UUID.fromString("4ff0055d-49a9-4e93-b960-ff70ae1007ce"));
mapppp.put(3, UUID.fromString("751c79ce-445c-406a-9787-a754857a259c"));
mapppp.put(3, UUID.fromString("dc721d77-509d-4bd3-8004-43a8daab5840"));
mapppp.put(3, UUID.fromString("4ca16aff-5a30-4638-8b38-3a93eddb0fc5"));
mapppp.put(3, UUID.fromString("e4be360b-cccb-42a2-b416-eb4bb623b49f"));
}
However, I cannot add another element for the repeated key value (for example 3) and I think I should implement something like Map<Integer, List<UUID>> map = new TreeMap<>(); rather than Map<Integer, UUID> map = new TreeMap<>();. However, I could not find a proper solution for that. So, how can I manage the repeated key values to be added to the map?
You could indeed use a Map<Integer, List<UUID>> as you suggested. You can then use computeIfAbsent to create an empty map if the key isn't there, and add the value to the key:
final Map<Integer, List<UUID>> map = new TreeMap<>();
addToMap(int key, String value) {
mapppp.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}

take value from a map of certain key and add it as another entrySet in another map

My first map
Map< String,Map< String,Object>> accounts = new HashMap< String,Map< String,Object>>();
Example :
{Entry01={DisplayName=Test01, ID=001, Status=A},
Entry01={DisplayName=Test02, ID=002, Status=T},
Entry52={DisplayName=Test52, ID=052, Status=A}}
My second map
Map< String,Set< String>> groupMap = new HashMap< String,Set< String>>();
Example :
{001=[Value01, Value02],
002=[Value08, Value09, Value15],
013=[Value58, Value89, Value90]}
Need to compare both these map and based on the ID key value from first map, I need to get the value from my second map and add it back to my first map with the key name and value.
I tired iterating through map but my map has many entries but only certain entry will have value.
If I understand your problem well, you need to get Set<String> corresponding to ID and add it to the same subMap as the ID :
Iterate throught the pairs
get back the ID
get the Set<String> from the ID
add the set to the value's pair
for (Map.Entry<String, Map<String, Object>> account : accounts.entrySet()) {
Map<String, Object> accountVal = account.getValue();
String id = accountVal.getOrDefault("ID", "").toString();
Set<String> setValues = entitlementMap.getOrDefault(id, Collections.emptySet());
accountVal.put("name", new HashSet<>(setValues));
}
With Code Demo you'll see the following content :
// From
Entry52={Status=A, DisplayName=Test52, ID=052}
Entry01={Status=A, DisplayName=Test01, ID=001}
Entry02={Status=T, DisplayName=Test02, ID=002}
// To
Entry52={Status=A, DisplayName=Test52, ID=052, name=[]}
Entry01={Status=A, DisplayName=Test01, ID=001, name=[Value01, Value02]}
Entry02={Status=T, DisplayName=Test02, ID=002, name=[Value15, Value09, Value08]}

For Each Loop in a Set

I have a HashTable with the following {4:1, 3:56, 4:3, 4:5, 9:89, etc.}
I then make the keys of this Table into a keyset by calling map.keySet().
How can I loop through that set to only output the values associated with the key of 4? I want the output to be 1,3,5, therefore I only want the values associated with the key 4? Is this possible, and if so how.
That's not how maps work. Maps typically only associate one value with each unique key value. So if you have a Map<Integer,Integer> myMap, calling myMap.put(4, newValue), where newValue is some integer, will overwrite the value that was previously mapped to 4. You can have duplicate values though, and you can print all known keys that have been mapped to that value in a map using the following loop.
for (Entry<Integer, Integer> entry : myMap.entrySet()) {
if (entry.getValue().equals(4)) {
System.out.println(entry.getKey());
}
}
A HashMap or a HashTable only maps a key to a value.
Option 1:
If you want to have multiple values for key store it as a list
Map<Integer, List<Integer>> myMap = new HashMap<>();
//To add value for a key
if (!myMap.containsKey(key)) {
myMap.put(new ArrayList<>());
}
myMap.get(key).add(value);
//Get
myMap.get(key); //This will give you the list of value for a given key and null if the key is not present
Option 2:
You can use Google Guava's MultiMap
You can use Google Guava Collections' MultiMap as it allows each key to associate with multiple values.
ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put(key, value);
Documentation can be found here: https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Multimap.html

Identify the Key-Value pair having duplicate values

I have a multimap like below:
{20014=[13123], 20013=[45451, 13123]}
where the keys and values are in String
If there is any duplicate in the value from other key, I have to print that key-value pair. In this case, it will be Key-20013,Value-13123.
How to achieve this?
I checked this link but not getting how to get the duplicate pair.
It could be done like this:
// Initialize my multimap
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("20014", "13123");
multimap.put("20013", "45451");
multimap.put("20013", "13123");
// Set in which we store the values to know if they exist already
Set<String> allValues = new HashSet<>();
// Convert the multimap into a Map
Map<String, Collection<String>> map = multimap.asMap();
// Iterate over the existing entries
for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
String key = entry.getKey();
Collection<String> values = entry.getValue();
// Iterate over the existing values for a given key
for (String value : values) {
// Check if the value has already been defined if so print a log message
if (!allValues.add(value)) {
System.out.println(String.format("Key-%s,Value-%s", key, value));
}
}
}
Output:
Key-20013,Value-13123
You can invert your multimap and, viewed as a map, iterate through its entries:
Multimap<String, String> inverse = Multimaps.invertFrom(multimap, HashMultimap.create());
for (Map.Entry<String, Collection<String>> entry : inverse.asMap().entrySet()) {
String value = entry.getKey();
Iterator<String> keysIterator = entry.getValue().iterator();
assert keysIterator.hasNext() : "there is always at least one key";
keysIterator.next(); // skip first key
while (keysIterator.hasNext()) { // each additional key is a duplicate
String key = keysIterator.next();
System.out.println(String.format("Key-%s,Value-%s", key, value));
}
}
Output:
Key-20013,Value-13123
If you are using an ImmutableMultimap then instead of Multimaps.invertFrom(Multimap, M) you can simply use ImmutableMultimap.inverse():
ImmutableMultimap<String, String> inverse = multimap.inverse();
If you simply want a map of duplicated values to their respective keys then you can use Maps.filterValues(Map, Predicate):
Map<String, Collection<String>> keysByDuplicatedValue = Maps.filterValues(inverse.asMap(),
keys -> keys.size() > 1);
Which will give you a map like below:
{13123=[20014, 20013]}

Categories

Resources