dhS
dhS

Reputation: 3694

How to filter inside map in java 8

static final List<String> ALL_TYPES = AuthInt.getScopeAssociations().stream()
    .map(a -> a.getLeft().getSimpleName())
    .collect(Collectors.toList());

There is a name "MarieAntra" in the the list which i want to add as Marie only .. How can i achieve this with Streams?

Upvotes: 2

Views: 135

Answers (3)

dreamcrash
dreamcrash

Reputation: 51393

One approach is to simply extract a method with that logic

public static String filterString(String s){
    return s.equals("MarieAntra") ? "Marie" : s;
}

and used on the Stream as follows:

AuthInt.getScopeAssociations().stream()
                              .map(a -> filterString(a))
                              .collect(Collectors.toList());

Or just directly on the Stream:

AuthInt.getScopeAssociations()
    .stream()
    .map(a -> a.getLeft().getSimpleName().equals("MarieAntra") 
                     ? "Marie" 
                     : a.getLeft().getSimpleName()
    )
    .collect(Collectors.toList());

Upvotes: 2

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

Inside map you can write a whole function as long as it returns the correct type, so there's no reason you couldn't write something as

static final List<String> ALL_TYPES = AuthInt.getScopeAssociations().stream()
  .map(a -> a.getLeft().getSimpleName())
  .map(name -> "MarieAntra".equals(name) ? "Marie" : name)
  .collect(Collectors.toList());

Upvotes: 2

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

Inside map you can write a whole function as long as it returns the correct type, so there's no reason you couldn't write something as

List<String> ALL_TYPES = AuthInt.getScopeAssociations().stream()

    .map(a -> {
                  if ("MarieAntra".equals(a.getLeft().getSimpleName())) return "Marie";
                  return a.getLeft().getSimpleName()
              }
   ).collect(Collectors.toList());

Upvotes: 1

Related Questions