0

How to write this type of code in java 8? I want to write this in Java8 using stream. Is there any way for this?

List<SomeDTO> someDTOList = sample.getSomeDTO(); int a=0; for(SomeDTO sample : someDTOList ){ String someElement = sample .getSomeElement (); if(someElement.equals("Condition1"){ a=1; break; } if(someElement.equals("Condition2"){ a=2; break; } if(someElement.equals("Condition3"){ a=3; break; } } 
2
  • 1
    what is sample doing? whst is not working? explain your question is detail Commented Sep 26, 2016 at 7:19
  • 2
    Rather than asking other people to do your assignment for you, attempt to write it yourself and ask here if you run into an actual problem. Commented Sep 26, 2016 at 7:24

1 Answer 1

2

You can do it with a combination of map, mapToInt, filter and findFirst, but it won't be so pretty :

int a = sample.getSomeDTO() .stream() .map(SomeDTO::getSomeElement) .mapToInt(e -> { if (e.equals("Condition1")) return 1; else if (e.equals("Condition2")) return 2; else if (e.equals("Condition3")) return 3; else return 0; }) .filter(a -> a > 0) .findFirst() .orElse(0); 

As Holger suggested, you can make it less ugly by replacing the if statements with ternary conditional expressions :

int a = sample.getSomeDTO() .stream() .map(SomeDTO::getSomeElement) .mapToInt(e -> e.equals("Condition1") ? 1 : e.equals("Condition2") ? 2 : e.equals("Condition3") ? 3 : 0) .filter(a -> a > 0) .findFirst() .orElse(0); 
Sign up to request clarification or add additional context in comments.

2 Comments

.mapToInt(e -> e.equals("Condition1")? 1: e.equals("Condition2")? 2: e.equals("Condition3")? 3: 0)
@Holger Much better :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.