You can use the join method from String class like below to get the string of ids seperated by '|' operator: String.join( new List<String>(String.join(new List<id>(setId), ',').split(',')) , '|' )); EDIT: check for isNotBlank for every entry in the for loop: public static string getString(Set<Id> setId){ String strId = ''; if(setId != null && setId.size() > 0 ) { for(Id RecordId :setId) { String strRecordId =''; if(String.isNotBlank(RecordId)){ strRecordId = RecordId; if(strRecordId.length() > 15){ strRecordId = strRecordId.substring(0,15); strRecordId = '\''+ strRecordId + '\''; strId += strRecordId + '|'; } } else{ strRecordId = '\' \''; strId += strRecordId + '|'; } } } strId = strId.removeEnd('|'); return strId ; }