java 8 - iterate 2 hash maps and create new hash map with records only matching keys - hashmap

we have a requirement to achieve in java8, please anyone help us.
we have method taking 2 parameters as input, both parameters are Hashmap<String,Dog>.
we want to iterate both hash maps and return one hashmap .
result hash Map contains only matched keys and corresponding values from 2 hashmaps, and (value for matched key) i.e Dog atributes we want to set some attribute from Hashmap1 and some attributes from hashmap2.
please suggest how we can achieve this in java 8.

You can implement the iterator simple like this:
public Map<String, Dog> combineMap(Map<String, Dog> first, Map<String, Dog> second) {
Map<String, Dog> result = new HashMap<>();
for (Map.Entry<String, Dog> entry : first.entrySet()) {
if(second.containsKey(entry.getKey())){
Dog dogFirst = entry.getValue();
Dog dogSecond = second.get(entry.getKey());
Dog combineDog = new Dog();
// Do what ever you want with combineDog
result.put(entry.getKey(), combineDog);
}
}
return result;
}

Related

Cucumber V5-V6 - passing complex object in feature file step

So I have recently migrated to v6 and I will try to simplify my question
I have the following class
#AllArgsConstructor
public class Songs {
String title;
List<String> genres;
}
In my scenario I want to have something like:
Then The results are as follows:
|title |genre |
|happy song |romance, happy|
And the implementation should be something like:
#Then("Then The results are as follows:")
public void theResultsAreAsFollows(Songs song) {
//Some code here
}
I have the default transformer
#DefaultParameterTransformer
#DefaultDataTableEntryTransformer(replaceWithEmptyString = "[blank]")
#DefaultDataTableCellTransformer
public Object transformer(Object fromValue, Type toValueType) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.convertValue(fromValue, objectMapper.constructType(toValueType));
}
My current issue is that I get the following error: Cannot construct instance of java.util.ArrayList (although at least one Creator exists)
How can I tell cucumber to interpret specific cells as lists? but keeping all in the same step not splitting apart? Or better how can I send an object in a steps containing different variable types such as List, HashSet, etc.
If I do a change and replace the list with a String everything is working as expected
#M.P.Korstanje thank you for your idea. If anyone is trying to find a solution for this here is the way I did it as per suggestions received. Inspected to see the type fromValue has and and updated the transform method into something like:
if (fromValue instanceof LinkedHashMap) {
Map<String, Object> map = (LinkedHashMap<String, Object>) fromValue;
Set<String> keys = map.keySet();
for (String key : keys) {
if (key.equals("genres")) {
List<String> genres = Arrays.asList(map.get(key).toString().split(",", -1));
map.put("genres", genres);
}
return objectMapper.convertValue(map, objectMapper.constructType(toValueType));
}
}
It is somehow quite specific but could not find a better solution :)

How to get objects from list by data from map with condition and save to another map using Groovy

Looking for solution how to match objects from list with data from map with condition if object field starts with map values and save to another map with Groovy
i have map with some data
Map<String, String> dataMap = new HashMap()
dataMap.put("d1", "DATA1")
dataMap.put("d2", "DATA2")
dataMap.put("d3", "DATA3")
and list of DataElement objects
List<DataElement> elements = new ArrayList()
elements.add(new DataElement("TEXT1"))
elements.add(new DataElement("TEXT2"))
elements.add(new DataElement("DATA1_text1"))
elements.add(new DataElement("DATA2_text2"))
class DataElement {
public field;
public DataElement(String text){
this.field = text
}
public getField(){
return this.field
}
And i'am trying to get new Map where keys are values from first map and values are objects(field) from List with condition if object field starts with map value: Result should be:
[d1=DATA1_text1, d2=DATA2_text2]
My code is working but may be there is more elegant variant with using collectEntries:
list = new HashMap()
mapping = dataMap.each { key, v ->
elements.each { el ->
if (el.getField().startsWith(v)) {
list.put(key, el)
}
}
}
dataMap.collectEntries{k,v->
[k,elements.find{e-> e.getField().startsWith(v)} ]
}.findAll{k,v-> v} //to keep only non empty values

Number name entity recognition in Stanford

I have a problem in which I'm trying to recognize the number name entity from a text using Stanford , in case I have for example 20 million It's retrieving like this "Number":["20-5","million-6"], How can I optimize the answer so 20 millions comes together? and How can I ignore the index number like (5,6) in the above example? I'm using java language.
public void extractNumbers(String text) throws IOException {
number = new HashMap<String, ArrayList<String>>();
n= new ArrayList<String>();
edu.stanford.nlp.pipeline.Annotation document = new edu.stanford.nlp.pipeline.Annotation(text);
pipeline.annotate(document);
List<CoreMap> sentences = document.get(CoreAnnotations.SentencesAnnotation.class);
for (CoreMap sentence : sentences) {
for (CoreLabel token : sentence.get(CoreAnnotations.TokensAnnotation.class)) {
if (!token.get(CoreAnnotations.NamedEntityTagAnnotation.class).equals("O")) {
if (token.get(CoreAnnotations.NamedEntityTagAnnotation.class).equals("NUMBER")) {
n.add(token.toString());
number.put("Number",n);
}
}
}
}
To get the exact text from any object of CoreLabel class simply use token.originalText() instead of token.toString()
If you need anything else from these tokens, take a look at CoreLabel's javadoc.

how to print a log for every element inserted into the HashMap?

I need to use an API which accepts hash map as an argument.
However, there was requirement to print a log whenever I insert a value for a key in the map. Values for the keys are assigned by reading from the external csv file.
For instance,
Map<String,String> myMap = new HashMap<String,String>();
myMap.put("nodeId", myMap.get("nodeIDForCreationOfTrackedAsset"));
myMap.put("templateAssetID", myMap.get("assetIdForServiceHistory"));
myMap.put("seqId", "{{db.WM_TS001.SeqNum}}");
myMap.put("badgeId", "{{db.WM_TS001.BadgeNum}}");
myMap.put("serialId","{{db.WM_TS001.SerialNum}}");
So everytime when I use myMap.put(key,value), it should print a log to an external file, some thing like below
element nodeId is assigned to "value" successfully.
element seqId is assigned to "value" successfully.
element templateAssetID is assigned to "value" successfully.
element badgeId is assigned to "value" successfully.
element serialId is assigned to "value" successfully.
Is there any generic way to do this, such that log can be printed through the program whenever myMap.put(key,value) is encountered.
The most obvious way to do this is to extend HashMap and then declare myMap to be an object of the new subclass. For example:
public class LoggingHashMap<K, V> extends HashMap<K, V> {
#Overrides
public V put(K key, V value) {
Log.i("LOG", "put:" + key + ":" + value;
return super.put(key, value);
}
}
Map<String, String> myMap = new LoggingHashMap<String, String>();

ordering of Hashtable in J2ME

I have some data and I have added them to Hashtable in some orders what I want to do now is to get the data in the same order that I have entered
What is the data type that I can use?
Assuming your key is a String you could add some ordering to it and have a getter method for the sorted data. See example below:
static int order;
Hashtable map = new Hashtable();
void put (String key, Object value) {
map.put(order + key, value);
order++;
}
Enumeration getSorted() {
Enumeration keys = map.keys();
Vector sortedKeys = new Vector();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
insertionSort(key, sortedKeys);
}
Vector sortedData = new Vector();
keys = sortedKeys.elements();
while (keys.hasMoreElements()) {
String key = (String) keys.nextElement();
sortedData.addElement(map.get(key));
}
return sortedData.elements();
}
You can find insertionSort algorithms at http://en.wikipedia.org/wiki/Insertion_sort
A Hashtable does not retain any ordering.
If you need insertion order access see if Linked Hash Map is offered in JavaME
You can download a source code of Java SE and make work LinkedHashMap in J2ME easily by removing generics (but also you might need to perform this on it's parent classes and interfaces).
You can find LinkedHashMap for Java ME here

Resources