Skip to content

Instantly share code, notes, and snippets.

@suzuki-hoge
Created May 12, 2020 13:38
Show Gist options
  • Save suzuki-hoge/337725c285b073b4ae0dfef70cb98814 to your computer and use it in GitHub Desktop.
Save suzuki-hoge/337725c285b073b4ae0dfef70cb98814 to your computer and use it in GitHub Desktop.
package bulk;
import javaslang.Tuple2;
import javaslang.collection.List;
public class Api {
public static void main(String[] args) {
String ids = List.of("id-1", "id-2", "id-3", "id-4", "id-5", "id-6", "id-7").mkString("\n");
List<Tuple2<String, String>> found = DB.find(List.of(ids.split("\n")));
System.out.println("result:");
System.out.println(
found.map(t -> t._1 + ", " + t._2).mkString("\n")
);
/*
out
select * from xxx where xxx in (id-1, id-2)
select * from xxx where xxx in (id-3, id-4)
select * from xxx where xxx in (id-5, id-6)
select * from xxx where xxx in (id-7)
result:
en-1, id-1
en-2, id-2
en-3, id-3
en-4, id-4
en-5, id-5
en-6, id-6
en-7, id-7
*/
}
}
package bulk;
import javaslang.Tuple2;
import javaslang.collection.List;
class DB {
static List<Tuple2<String, String>> find(List<String> ids) {
return chunk(ids, List.empty()).flatMap(DB::_find);
}
private static List<List<String>> chunk(List<String> xs, List<List<String>> acc) {
if (xs.nonEmpty()) {
Tuple2<List<String>, List<String>> sp = xs.splitAt(2);
return chunk(sp._2, acc.append(sp._1));
} else {
return acc;
}
}
static private List<Tuple2<String, String>> _find(List<String> ids) {
System.out.println("select * from xxx where xxx in (" + ids.mkString(", ") + ")");
// sql in fact
return ids.map(id -> "en-" + id.split("-")[1]).zip(ids);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment