azaveri7
azaveri7

Reputation: 899

how to tackle a special condition in map of java8 streams

I have a Question class as follows:

public class Question {
    private String name;
    private String type;
    private boolean isAdded;
    ...
    getters and setters
}

I want all questions from a list of questions whose isAdded=true appended by ':' and if question name is Special than in that case Special-type value.

The final String should look like this:

questionname1:questionname2:Special-type value:questionname4

I have written:

List<String> slist = questionList.stream().filter(q -> q.isAdded() == true).map(name-> name.getName()).collect(Collectors.toList());

String final = String.join(":", slist);

I get all string names appended by : but do not get type value if question name is Special.

Please let me know what changes should be made.

Upvotes: 2

Views: 65

Answers (2)

pvpkiran
pvpkiran

Reputation: 27038

This should work

  list.stream()
      .filter(Question::isAdded)
      .map(item-> item.getName().equals("Special") ? item.getType() : item.getName())
      .collect(Collectors.joining(":"))

Upvotes: 4

Eran
Eran

Reputation: 393811

You can include a condition in the lambda expression passed to map():

.map(q -> q.getName().equals("Special") ? "Special-type value" : q.getName())

And the full Stream pipeline would be:

List<String> slist = 
    questionList.stream()
                .filter(q -> q.isAdded())
                .map(q -> q.getName().equals("Special") ? "Special-type value" : q.getName())
                .collect(Collectors.toList());

BTW, if you want to join the List to a single String, you can do it directly:

String finalValue = 
    questionList.stream()
                .filter(q -> q.isAdded())
                .map(q -> q.getName().equals("Special") ? "Special-type value" : q.getName())
                .collect(Collectors.joining(":"));

P.S. it wasn't clear from your phrasing if you wanted the String "Special-type value" to be used when the name is "Special", or to use some other value which you didn't specify how to obtain.

Upvotes: 1

Related Questions