0

I have string which contain number of department separated by comma. I have to feed this data to sql 'IN' clause.

I want conditional check for last element, I do not want to append 'comma' after last element. I don`t know how to use condition inside java 8 forEach loop.

public String  getDeptInClauseParameters(String depts){
       StringBuilder deptsInParameter= new StringBuilder();
       Stream<String>  stream= Arrays.stream(depts.split(","));
       stream.forEach(dept ->  deptsInParameter.append("'").append(dept).append("' , "));
        return deptsInParameter.toString();
    }
sar
  • 1,277
  • 3
  • 21
  • 48

1 Answers1

2

You can use the Collectors.joining(delimiter, prefix, suffix).

  • delimiter the delimiter to be used between each element
  • prefix the sequence of characters to be used at the beginning of the joined result
  • suffix the sequence of characters to be used at the end of the joined result

Example:-

    String depts = "Dept1,Dept2";
    Stream<String> stream = Arrays.stream(depts.split(","));

    System.out.println(stream.collect(Collectors.joining("','", "'", "'")));

This will print 'Dept1','Dept2'as output, hope it helps

Jobin
  • 5,610
  • 5
  • 38
  • 53