Convert Map to Custom Map - java

Map<String, String> characterMap = new HashMap<>();
characterMap.put("Manikanta", "Pretty");
characterMap.put("Amulya", "VeryGood");
characterMap.put("Saroja", "Good");
characterMap.put("Vinitha", "Cool");
characterMap.put("Sravani", "Good");
characterMap.put("Sameera", "Good");
/*String key = characterMap.entrySet().stream().filter(entry -> entry.getValue().equalsIgnoreCase("Good")).map(Map.Entry::getKey).findFirst().orElse(null);*/
Map<String, String> comboMap = new HashMap<>();
String newKey = null;
String val1 = null;
String val2 = null;
for (Map.Entry<String, String> entry : characterMap.entrySet()) {
if (entry.getKey().equalsIgnoreCase("Manikanta"))
newKey = entry.getKey();
if (entry.getKey().equalsIgnoreCase("Amulya"))
val1 = entry.getValue();
if (entry.getKey().equalsIgnoreCase("Vinitha"))
val2 = entry.getValue();
}
comboMap.put(newKey, val1 + "_" + val2);
How can I implement this in a lambda expression? Is it really possible to insert existing map data to customize to add new map like the above code?

You can't.
You're attempting to reduce a map with 6 elements into, evidently, a map with a single element in it (if this is an example, and the resulting map will ever contain anything but exactly 1 key of value "Manikanta" -> "VeryGood_Cool", you're going to need to update your example).
streams (I gather that is what you mean by 'in lambda expression') excel at operating on a single element in the stream (so, say, the notion "Saroja"->"Good"), or on how to turn the entire stream into a different collection (such as: Turn the whole thing into a list of keys).
You could write a custom collector; it would not be any shorter than this code is, and would be a lot harder to read. Hence I don't see the point of showing that.

Since you only check on the key values, you don't even need a for loop:
comboMap.put(characterMap.containsKey("Manikanta")?"Manikanta":null,
characterMap.get("Amulya")+ "_" + characterMap.get("Vinitha"));

Related

How to put together multiple Maps <Character, Set<String>> without overriding Sets

In my project I am using two maps Map<Character, Set<String>>.
map1 - is temporally holding needed values
map2 - is summing all data from map1 after each loop
for example i got:
map2 = (B; Beryllium, Boron, Bromine)
map2 = (H; Hellum, Hydrogen, Hafnium)
now new map1 is:
map1 = (B; Bismuth)
map1 = (O; Oxygen)
In my code adding Oxygen as new entry is ok, but adding new entry for B ends by overraidding existing data in values and leave me only Bismuth.
My code:
while (iterator.hasNext()) {
Set<String> words = new TreeSet<>();
String word = iterator.next();
char[] wordChars = word.toCharArray();
//some code
words.add(word);
map1.put(wordChars[i], words);
}
map2.putAll(map1);
I tought about using .merge but I have no idea how to use it with Sets as values, and I cannot use simple Strings with concat.
You can use Map#merge like this:
Map<String, Set<String>> map1; // [key="B";values=["Beryllium", "Boron", "Bromine"]]
Map<String, Set<String>> map2; // [key="B";values=["Bismuth"] key="I";values=["Iron"]]
for (Entry<String, Set<String>> entry : map2.entrySet()) {
map1.merge(entry.getKey(), entry.getValue(), (s1, s2) -> {s1.addAll(s2); return s1;});
}
//map1 = [key="B";values=["Beryllium", "Boron", "Bromine", "Bismuth"] key="I";values=["Iron"]]
Map::compute is probably what you're looking for. This gives you a way to map any existing value (if there is one), or provide one if not.
For example, in your case something like the following would probably suffice:
oldMap.compute("B", current -> {
if (current == null) {
// No existing entry, so use newMap's one
return newMap.get("B");
} else {
// There was an existing value, so combine the Sets
final Set<String> newValue = new HashSet<>(current);
newValue.addAll(newMap.get("B"));
return newValue;
}
});
There's also MultiValueMap and Multimap from spring and guava respectively (if you're ok bringing in dependencies) which cover this case with less work already.
Temporary map1 will not be needed in this case. Get the set for that character, if null create a new set. Add the word to that set and put in the map:
while (iterator.hasNext()) {
String word = iterator.next();
//some code
Set<String> words = map2.get(word.charAt(0));
if(words == null) {
words = new TreeSet<>();
}
words.add(word);
map2.put(word.charAt(0), words);
}
When using the merge() function, if the specified key is not already associated with a value or the value is null, it associates the key with the given value.
Otherwise, i.e if the key is associated with a value, it replaces the value with the results of the given remapping function. So in order to do not overwrite the old value you must write your remapping function so that it combines the old and new values.
To do so replace this line :
map2.putAll(map1);
with
map1.forEach( (key, value)->{
map2.merge(key, value, (value1,value2) -> Stream.of(value1,value2)
.flatMap(Set::stream)
.collect(Collectors.toSet()));
});
This will iterate over map1 and add echh key which is not present into map2 and associate it with the given value and for each key which is already present it combines the old values and new values.
Alternative you can also work with Map.computeIfPresent and Map.putIfAbsent
map1.forEach( (key, value)->{
map2.computeIfPresent(key, (k,v) -> Stream.of(v,value).flatMap(Set::stream).collect(Collectors.toSet()));
map2.putIfAbsent(key, value);
});

Create Map with provided set of keys and default values for them

I have a method that receives List<String> keys and does some computations on these and at the end it returns Map<String, String> that has keys from that List and values computed or not. If value cannot be computed I want to have empty String for that key.
The clearest way would be to create Map containing all the keys with default values (empty String in that case) at the start of computations and then replace computed values.
What would be the best way to do so? There is no proper initializer in Collections API I think.
The easiest answer came to me seconds ago:
final Map<String, String> labelsToReturn = keys.stream().collect(toMap(x -> x, x -> ""));
solves the problem perfectly.
Just use stream and toMap with key / value mapping to initialize the map.
I advise you to use Stream API Collectors.toMap() method. There is a way:
private static void build(List<String> keys) {
Map<String, String> defaultValues = keys.stream().collect(
Collectors.toMap(key -> key, key -> "default value")
);
// further computations
}
Map<String,String> map = new HashMap<>();
String emptyString = "";
for(String key:keys){
Object yourcomputation = emptyString;
//asign your computation to new value base on key
map.put(key,yourcomputation);
}

Java 8 way to convert collection into one key multiple values map

Any way to perform the below code using Java 8.
final Map<String, Collection<ProductStrAttributeOverrideRulesModel>> attributeRulesMap = new HashMap<String, Collection<ProductStrAttributeOverrideRulesModel>>();
for (final ProductStrAttributeOverrideRulesModel rule : rules)
{
final String key = rule.getProductStrAttributeOverride().getProductStrTypeField().getAttributeDescriptorQualifier();
if (attributeRulesMap.containsKey(key))
{
final Collection<ProductStrAttributeOverrideRulesModel> currentRules = attributeRulesMap.get(key);
currentRules.add(rule);
}
else
{
final Collection<ProductStrAttributeOverrideRulesModel> list = new LinkedList<ProductStrAttributeOverrideRulesModel>();
list.add(rule);
attributeRulesMap.put(key, list);
}
}
if it is only
final Map<String, ProductStrAttributeOverrideRulesModel> attributeRulesMap
than i can do like following but i need to arrange the whole collection inside a map based on key and each key can have multiple values stored in collection.
Map<String, ProductStrAttributeOverrideRulesModel> result =
choices.stream().collect(Collectors.toMap(ProductStrAttributeOverrideRulesModel::getProductStrAttributeOverride.getProductStrTypeField.getAttributeDescriptorQualifier,
Function.identity()));
You could use groupingBy :
Map<String,List<ProductStrAttributeOverrideRulesModel>>
map =
choices.stream()
.collect(Collectors.groupingBy(rule -> rule.getProductStrAttributeOverride().getProductStrTypeField().getAttributeDescriptorQualifier()));
And if you don't want a List, you can pass a second argument to groupingBy and specify whatever Collection you want. For example :
Map<String,Collection<ProductStrAttributeOverrideRulesModel>>
map =
choices.stream()
.collect(Collectors.groupingBy(rule -> rule.getProductStrAttributeOverride().getProductStrTypeField().getAttributeDescriptorQualifier(),
Collectors.toCollection(HashSet::new)));
Note that it doesn’t always have to be a Stream operation. Your code would also benefit from using the “diamond operator” (though not new to Java 8) and from using new collection operations, i.e. computeIfAbsent, which allows to elide the entire conditional inside the loop and its code duplication. Putting both together, you’ll get:
final Map<String, Collection<ProductStrAttributeOverrideRulesModel>>
attributeRulesMap = new HashMap<>();
for(final ProductStrAttributeOverrideRulesModel rule: rules)
{
final String key = rule.getProductStrAttributeOverride()
.getProductStrTypeField().getAttributeDescriptorQualifier();
attributeRulesMap.computeIfAbsent(key, x->new LinkedList<>()).add(rule);
}
You could also replace the loop by a forEach invocation, if you wish:
rules.forEach(rule -> attributeRulesMap.computeIfAbsent(
rule.getProductStrAttributeOverride()
.getProductStrTypeField().getAttributeDescriptorQualifier(),
x->new LinkedList<>()).add(rule)
);
though it’s debatable whether this is an improvement over the classical loop here…

in Java, how can I map String to a Set<String> if I do not know how many keys in total

I need a HashMap, which the key is String and value is Set, like:
Key: "a", Value: {"a","b","c"....}
Key: "b", Value: {"a,","d"....}
...
But I do not know how many keys in total, it depends on the result from other method.
So basically, here is the method looks like: (map could be field)
public void mapKeyValue(int numbersOfKey, HashMap map){
//some code
}
So if I write the code like this:
public void mapKeyValue(int numbersOfKey, HashMap map){
for (int i = 0; i < numbersOfKey; i++){
Set<String> set = new HashSet<String>();
set.add("some strings");// we can add some strings here
map.put("OneString", set);
}
}
After the method, I will get nothing because I will lose all the Set object created by the method, so I cannot get the Set by calling map.get("OneString").
So what should I do if I want to get that hashMap?
There are a number of issues with your code, but I suggest the following approach.
In your case, it looks like you have a Map<String, Set<String>> which is a map of String keys to a set of Strings.
If that's what you were after, I suggest that you
check if the key has a value. If not add an empty set for the key to the surrounding map.
Fetch the set from the map by it's key.
add or remove any desired values from the set
Note that your code as it is written, always replaces the Set stored with the key "OneString" meaning that regardless of value "numbersOfKey" you are really just rebuilding the set at the single key "OneString" numbersOfKey times.
You probably want to do something like
public void addToSet(String setName, String value) {
if (!sets.containsKey(setName)) {
sets.put(setName, new HashSet<String>());
}
Set<String> values = sets.get(setName);
values.add(value);
}
This block assumes you have somewhere in the class a member variable like
private Map<String, Set<String>> sets = new HashMap<>();
Note that this code is an idea, and not production code. In the real world, what you add probably should eventually be removed at some point in time. As such, you want to have a facility to remove specific values, or entire sets of values along with their keys at some future point of your program's execution.
you can not do that?
public HashMap<String, Set<String>> mapKeyValue(int numbersOfKey){
HashMap<String, Set<String>> map = new HashMap<>();
for (int i = 0; i < numbersOfKey; i++){
Set<String> set = new HashSet<String>();
set.add("some strings" + "" + i);// we can add some strings here
map.put("OneString", set);
}
return map;
}
I would suggest using the Apache Commons Collection MultiValueMap instead of creating a Set each time. Both work just fine, but there is a Map that does all of that for you and it's based on a HashMap, keeping your constant time access. Javadoc here:
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/map/MultiValueMap.html
Something like this...
public void someOtherMethod() {
// Assuming the Map is created and used somewhere outside the mapKeyValue method. Otherwise it should be instantiated inside the mapKeyValue method
MultiValueMap<String, String> map = new MultiValueMap<>();
//2 is an arbitrary, made up number that you select somehow
mapKeyValue(2, map);
//Access the values of the map dynamically without knowing how many keys there are
for (String key : map.keySet()) {
System.out.print(key + " : ");
for (String value : map.getCollection(key)) {
System.out.print(value + ", ");
}
}
}
public MultiValueMap<String, String> mapKeyValue(int numbersOfKey, MultiValueMap<String, String> map){
for (int i = 0; i < numbersOfKey; i++){
//We need to create a unique key here, so let's use 'i'
//There are several ways to skin the cat and get the int to String
//Also want to create unique values, but that's up to you, they're not required to be unique
map.put(Integer.toString(i), Integer.toString(i) + "a");
map.put(Integer.toString(i), Integer.toString(i) + "b");
map.put(Integer.toString(i), Integer.toString(i) + "c");
}
//At this point, the map has in it the following key : value pairs
//"0" : ["0a", "0b", "0c"]
//"1" : ["1a", "1b", "1c"]
//"2" : ["2a", "2b", "2c"]
//Not technically required to return the map IFF the map is instantiated outside the method
return map;
}

Concatenating two hashmaps without removing common entires from both the maps

I have two hashmaps, in particular vocabs of two languages say english and german.I would like to concatenate both these map to return a single map.I tried :
hashmap.putall()
But, removed some of the entries which are common in both maps and replace it by single entry only.But i want to keep both the vocabs intact just concatenate those. Is there any method to do it? if not any other way to do. I would prefer any methods in hashmap.
[EDIT]
To make more clear, lets see two maps
at the 500 um die 500
0 1 2 0 1 2
resutls into
at the 500 um die 500
0 1 2 3 4 5
You'll have to write your own custom "putAll()` method then. Something like this would work:
HashMap<String> both = new HashMap<String>(english);
for(String key : german.keySet()) {
if(english.containsKey(key)) {
both.put(key, english.get(key)+german.get(key));
}
}
This first copies the English HashMap. Then puts in all the German words, concatenating if there is a duplicate key. You might want some kind of separator character like a / in between so you can later extract the two.
There isn't anything like that in the Java main library itself, you will have to use something provided by third parties like Google Guava's Multimap, it does exactly what you want, or build something like this manually.
You can download the Guava library at the project's website. Using a multimap is the same as using a map, as in:
Multimap<String,String> both = new ArrayListMultimap <String,String>();
both.putAll( german );
both.putAll( english);
for ( Entry<String,String> entry : both.entrySet() ) {
System.out.printf( "%s -> %s%n", entry.getKey(), entry.getValue() );
}
This code will print all key-value pairs including the ones that are present on both maps. So, if you have me->me at both german and english they would be printed twice.
You cannot do that directly with any Map implementation, since in a map, each key is unique.
A possible workaround is to use Map<Key, List<Value>>, and then do the concatenation of your maps manually. The advantage of using a List for the concatenated map, is that it will be easy to retrieve each of the individual values without any extra fiddling.
Something like that would work:
public Map<Key, List<Value>> concat(Map<Key, Value> first, Map<Key, Value> second){
Map<Key, List<Value>> concat = new HashMap<Key, List<Value>>();
putMulti(first, concat);
putMulti(second, concat);
return concat;
}
private void putMulti(Map<Key, Value> content, Map<Key, List<Value>> dest){
for(Map.Entry<Key, Value> entry : content){
List<Value> vals = dest.get(entry.getKey());
if(vals == null){
vals = new ArrayList<Value>();
dest.put(entry.getKey(), vals);
}
vals.add(entry.getValue());
}
}
Similar to #tskuzzy's answer
Map<String, String> both = new HashMap<String, String>();
both.putAll(german);
both.putAll(english);
for (String e : english.keySet())
if (german.containsKey(e))
both.put(e, english.get(e) + german.get(e));
Slight improvisation of #tskuzzy and #Peter's answer here. Just define your own StrangeHashMap by extending HashMap.
public class StrangeHashMap extends HashMap<String, String> {
#Override
public String put(String key, String value) {
if(this.containsKey(key)) {
return super.put(key, super.get(key) + value);
} else {
return super.put(key, value);
}
}
}
You can use it as so:
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "Value1");
map1.put("key2", "Value2");
Map<String, String> map2 = new HashMap<String, String>();
map2.put("key1", "Value2");
map2.put("key3", "Value3");
Map<String, String> all = new StrangeHashMap();
all.putAll(map1);
all.putAll(map2);
System.out.println(all);
The above prints the below for me:
{key3=Value3, key2=Value2, key1=Value1Value2}
Given the new elements in the question, it seems that what you actually need to use is lists. In this case, you can just do:
List<String> english = ...;
List<String> german = ...;
List<String> concat = new ArrayList<String>(english.size() + german.size());
concat.addAll(english);
concat.addAll(german);
And there you are. You can still use concat.get(n) to retreive the value nth value in the concatenated list.

Categories

Resources