tweetysat
tweetysat

Reputation: 2403

Java 8 Stream extract datas from Map

I have a Map<String,ExtractedData> extractedDatas and I want to extract some data as return result. I'm quite new with the Stream API and I don't understand what I have to do. 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 ?

Upvotes: 3

Views: 2195

Answers (2)

Eugene
Eugene

Reputation: 120968

you could do it a bit different if you are OK altering the initial Map:

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

Upvotes: 1

Eran
Eran

Reputation: 393936

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.

In your case it's simply the key and the value of the Map.Entry elements of the Stream.

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

Upvotes: 7

Related Questions