简体   繁体   English

Java 8 Stream从Map中提取数据

[英]Java 8 Stream extract datas from Map

I have a Map<String,ExtractedData> extractedDatas and I want to extract some data as return result. 我有一个Map<String,ExtractedData> extractedDatas ,我想提取一些数据作为返回结果。 I'm quite new with the Stream API and I don't understand what I have to do. 我对Stream API很新,我不明白我必须做什么。 I tried with 我试过了

public Map<String,ExtractedData> getExtractedData(String name)
{
    return extractedDatas.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(name))
            .filter(entry -> entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
            .collect(Collectors.toMap(...);
}

What do I have to put in the Collectors.toMap ? 我需要在Collectors.toMap什么?

You simply have to pass the functions that map an element of your Stream to both the key and the value of the output Map . 您只需通过你的元素映射功能Stream的密钥和输出的值都Map

In your case it's simply the key and the value of the Map.Entry elements of the Stream. 在您的情况下,它只是Stream的Map.Entry元素的键和值。

public Map<String,ExtractedData> getExtractedData(String name)
{
    return extractedDatas.entrySet().stream()
            .filter(entry -> entry.getKey().startsWith(name))
            .filter(entry -> entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
            .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
}

you could do it a bit different if you are OK altering the initial Map : 如果你可以改变初始Map你可以做的有点不同:

extractedDatas
     .entrySet()
     .removeIf(entry -> 
                 !(entry.getKey().startsWith(name) || 
                   entry.getValue().getFieldValue() != null && entry.getValue().getFieldValue() != "")
                  )
              );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM