gpt4 book ai didi

java - 如何使用 Java 8 Streams 将列表中的对象与具有条件的 map 中的数据进行匹配并保存到另一个 map

转载 作者:行者123 更新时间:2023-11-30 07:40:11 25 4
gpt4 key购买 nike

寻找解决方案,如果对象字段以 map 值开头并保存到另一个 map ,如何将列表中的对象与 map 中的数据进行匹配

我有一些数据的 map

Map<String, String> dataMap = new HashMap()
dataMap.put("d1", "DATA1")
dataMap.put("d2", "DATA2")
dataMap.put("d3", "DATA3")

和 DataElement 对象列表

    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
}


}

我正在尝试获取新 map ,其中键是第一个 map 中的值,值是列表中的对象(字段),条件是对象字段以 map 值开头:结果应该是:

[d1=DATA1_text1, d2=DATA2_text2]  

我的代码:

    Map<String, String> collect2 = dataMap.entrySet().stream()
.filter({ map -> elements.stream()
.anyMatch({ el -> el.getField().startsWith(map.getValue()) })})
.collect(Collectors.toMap(KEY, VALUE))

最佳答案

希望我答对了问题:

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));

您正在处理输入 Map 的条目,并且仅保留具有与 List 的元素匹配的值的条目(通过 filter(),虽然你有一些语法错误),但你需要将输入条目映射到包含所需新值的新条目。

上面的代码生成了 Map

{d1=DATA1_text1, d2=DATA2_text2}

对于给定的输入。

关于java - 如何使用 Java 8 Streams 将列表中的对象与具有条件的 map 中的数据进行匹配并保存到另一个 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58049693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com