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

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


我有带有一些数据的地图


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,其中键是第一个映射中的值,值是列表中的对象(字段),条件是如果对象字段以映射值开头:结果应该是:


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


SMILET
浏览 107回答 1
1回答

慕容森

希望我的问题是正确的:Map<String, String> collect2 =&nbsp;&nbsp; &nbsp; dataMap.entrySet()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(e -> elements.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // this will search for the first element of the List matching&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // the value of the current Entry, if exists&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(el -> el.getField().startsWith(e.getValue()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .findFirst()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // this will create a new Entry having the original key and the&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // value obtained from the List&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .map(el -> new SimpleEntry<>(e.getKey(),el.getField()))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // if findFirst found nothing, map to a null element&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .orElse(null))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(Objects::nonNull) // filter out all the nulls&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));您正在处理 input 的条目Map,并仅保留具有与 的元素匹配的值的条目List(通过filter(),尽管有一些语法错误),但您需要将map输入条目转换为包含所需新值的新条目。上面的代码产生Map{d1=DATA1_text1, d2=DATA2_text2}对于给定的输入。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java