Reputation: 399
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
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:
Map<String, String> collect2 = dataMap.entrySet().stream()
.filter({ map -> elements.stream()
.anyMatch({ el -> el.getField().startsWith(map.getValue()) })})
.collect(Collectors.toMap(KEY, VALUE))
Upvotes: 2
Views: 2767
Reputation: 393936
Hopefully I got the question right:
Map<String, String> collect2 =
dataMap.entrySet()
.stream()
.map(e -> elements.stream()
// this will search for the first element of the List matching
// the value of the current Entry, if exists
.filter(el -> el.getField().startsWith(e.getValue()))
.findFirst()
// this will create a new Entry having the original key and the
// value obtained from the List
.map(el -> new SimpleEntry<>(e.getKey(),el.getField()))
// if findFirst found nothing, map to a null element
.orElse(null))
.filter(Objects::nonNull) // filter out all the nulls
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
You are processing the entries of the input Map
, and keep only entries having a value that matches an element of the List
(via filter()
, though you have some syntax errors), but you need to map
the input entries into new entries that contain the desired new value.
This above code produces the Map
{d1=DATA1_text1, d2=DATA2_text2}
for the given input.
Upvotes: 3