2

I want to convert a HashSet of Integer to Comma Separated String,

so I can use the same in where clause of a MySQL query.

//[MySQL - Sample table Schema]
my_table
state_id INTEGER
shop_id INTEGER
Set<Integer> uniqueShopIds = shopService.GetShopIds(); // This returns HashSet<Integer>
String inClause = ; // **How do i convert the uniqueShopIds to comma separated String**
String selectQuery = String.format("SELECT DISTINCT(state_id) FROM my_table WHERE shop_id IN (%s);", inClause);

If there's any other way, I can use the HashSet directly in IN CLAUSE of the PreparedStatment, please share.

Manikandaraj Srinivasan
  • 3,557
  • 5
  • 35
  • 62

2 Answers2

7
Set<Integer> s = new HashSet<>(Arrays.asList(1, 2, 3));
String str = s.stream().map(Object::toString).collect(Collectors.joining(","));
System.out.println(str); // prints 1,2,3
Mark Bramnik
  • 39,963
  • 4
  • 57
  • 97
0

Then there is this.

Set<Integer> s = new HashSet<>(Arrays.asList(1, 2, 3));

The default toString for a collection is a csv surrounded by []

So skip the first one and remove the last one

String str = s.toString().substring(1).replace("]","");

Or just take the substring in between

String str = s.toString();
str = str.substring(1,str.length()-1);

System.out.println(str);

Both would result in

1, 2, 3
WJS
  • 36,363
  • 4
  • 24
  • 39