There is an Integer sheet, I want to make a string out of it using stream, but with the condition that if the number is greater than 10, then add to the string "> 10," and if less, then "<10,". I wrote the code for the case if the number is greater than 10:

String str = list.stream().filter(i -> i > 10).map(i -> i.toString()).collect(Collectors.joining("> 10, ")); 

I can not understand how to add the second condition for "<10," in stream. And the second question is why joining ("> 10,") does not work for the last element. I would be grateful if you could help me.

    1 answer 1

     list.stream() .map(i -> i < 10 ? i + " < 10" : i + " > 10") .collect(Collectors.joining(", ")); 
    • Oh, right. Thank you very much! - Artem
    • if you can, one more question: I understand correctly that for Collectors.joining you can’t use a ternary operation to determine which suffix to use, depending on the last element? - Artem
    • If not, then I will look for another way - Artem
    • one
      It is impossible. Only if you write your collector. - Sergey Gornostaev
    • What if i == 10? - Sergey