如何在 Java 中将整数的 HashSet 转换为逗号分隔的字符串

Man*_*san 3 java hashset

我想将整数的哈希集转换为逗号分隔的字符串,

所以我可以在 MySQL 查询的 where 子句中使用相同的内容。

//[MySQL - Sample table Schema]
my_table
state_id INTEGER
shop_id INTEGER
Run Code Online (Sandbox Code Playgroud)
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);
Run Code Online (Sandbox Code Playgroud)

如果还有其他方法,我可以直接在PreparedStatment的IN CLAUSE中使用HashSet,请分享。

Mar*_*nik 9

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
Run Code Online (Sandbox Code Playgroud)