Javaのスニペット集
このページは、Javaのスニペットなどをまとめる予定のページです。
注意
- コードのライセンスは CC0 (クレジット表示不要、改変可、商用可) です。
- Java 11以上を想定しています。
スニペット
文字列
フォーマット
int a = 1;
int b = 2;
String s = String.format("a = %d, b = %d", a, b); // a = 1, b = 2
パディング
int a1 = 1;
String s1 = String.format("%04d", a1); // 0001
String a2 = "1";
String s2 = String.format("%4s", a2).replace(' ', '0'); // 0001
int a = 1; // String a = "1"; でも同じ
String s = String.format("%-4s", a).replace(' ', '0'); // 1000
文字列の検索
String s = "test string";
boolean b = s.matches(".*str.*");
String s = "test string";
boolean b = s.startsWith("test");
String s = "test string";
boolean b = s.endsWith("ing");
数値変換
String s = "123";
int n = Integer.parseInt(s);
String s = "123.45";
double n = Double.parseDouble(s);
List
List<String> list1 = List.of("a", "b", "c", "d");
Map
Map<String, String> map1 = Map.of("a", "b", "c", "d"); // {a=b, c=d}
Map<String, String> map1 = Map.ofEntries(Map.entry("a", "b"), Map.entry("c", "d")); // {a=b, c=d}
Stream
List<Map<String, Object>> list1 = List.of(
Map.of("name", "taro", "age", 20),
Map.of("name", "jiro", "age", 10),
Map.of("name", "hanako", "age", 19));
String name = list1.stream()
.map(x -> (String)x.get("name"))
.collect(Collectors.joining(", ")); // taro, jiro, hanako
List<Map<String, Object>> list1 = List.of(
Map.of("name", "taro", "age", 20),
Map.of("name", "jiro", "age", 10),
Map.of("name", "hanako", "age", 19));
List<Map<String, Object>> list2 = list1.stream()
.filter(x -> (Integer)x.get("age") >= 15) // フィルタ
.collect(Collectors.toList());
List<Map<String, Object>> list1 = List.of(
Map.of("name", "taro", "age", 20),
Map.of("name", "jiro", "age", 10),
Map.of("name", "hanako", "age", 19));
List<Map<String, Object>> list2 = list1.stream()
.sorted(Comparator.comparing(x -> (Integer)x.get("age"))) // ageでソート
.collect(Collectors.toList());
List<Map<String, Object>> list1 = List.of(
Map.of("name", "taro", "age", 20),
Map.of("name", "jiro", "age", 10),
Map.of("name", "hanako", "age", 19));
List<Map<String, Object>> list2 = list1.stream()
.sorted(Comparator.comparing((Map<String, Object> x) -> (Integer)x.get("age")).reversed()) // ageで逆順ソート
.collect(Collectors.toList());
正規表現
String s = "20220102";
if (s.matches("[0-9]{8}")) {
}
String s = "20220102";
Matcher m = Pattern.compile("([0-9]{4})([0-9]{2})([0-9]{2})").matcher(s);
if (m.matches()) {
String yyyy = m.group(1);
String mm = m.group(2);
String dd = m.group(3);
}
String s = "20220102";
Matcher m = Pattern.compile("(?<yyyy>[0-9]{4})(?<mm>[0-9]{2})(?<dd>[0-9]{2})").matcher(s);
if (m.matches()) {
String yyyy = m.group("yyyy");
String mm = m.group("mm");
String dd = m.group("dd");
}
String s1 = "abc123abc";
String s2 = s1.replaceAll("^abc", ""); // 123abc
var map = Map.of("a", "test1", "b", "test2");
// "{a} {b} {c}" -> "test1 test2 {c}"
String s = Pattern.compile("\\{(.+?)\\}").matcher("{a} {b} {c}").replaceAll(x -> {
return map.getOrDefault(x.group(1), x.group(0));
});
日時
現在日時
Instant now = Instant.now();
パース
Instant t = Instant.parse("2022-01-02T03:04:05+09:00"); // ISO 8601。値はUTCとして扱われる
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.of("Asia/Tokyo"));
Instant t2 = formatter.parse("20220102030405", Instant::from); // 指定形式。値はUTCとして扱われる
LocalDateTime t = LocalDateTime.parse("2022-01-02T03:04:05"); // ISO 8601
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
LocalDateTime t2 = LocalDateTime.parse("20220102030405", formatter); // 指定形式
LocalDateTime t3 = formatter.parse("20220102030405", LocalDateTime::from); // 上と同じ
OffsetDateTime t = OffsetDateTime.parse("2022-01-02T03:04:05+09:00"); // ISO 8601
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.ofHours(9));
OffsetDateTime t2 = OffsetDateTime.parse("20220102030405", formatter); // 指定形式
OffsetDateTime t3 = formatter.parse("20220102030405", OffsetDateTime::from); // 上と同じ
ZonedDateTime t = ZonedDateTime.parse("2022-01-02T03:04:05+09:00"); // ISO 8601
ZonedDateTime t2 = ZonedDateTime.parse("2022-01-02T03:04:05+09:00[Asia/Tokyo]"); // タイムゾーン付き
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.of("Asia/Tokyo"));
ZonedDateTime t3 = ZonedDateTime.parse("20220102030405", formatter); // 指定形式
ZonedDateTime t4 = formatter.parse("20220102030405", ZonedDateTime::from); // 上と同じ
LocalDate d = LocalDate.parse("2022-01-02"); // ISO 8601
LocalDate d = LocalDate.parse("20220102", DateTimeFormatter.BASIC_ISO_DATE); // ISO 8601 (基本形式)
フォーマット
Instant t = Instant.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.of("Asia/Tokyo"));
String s = formatter.format(t);
LocalDateTime t = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String s = formatter.format(t);
OffsetDateTime t = OffsetDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneOffset.ofHours(9));
String s = formatter.format(t);
ZonedDateTime t = ZonedDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").withZone(ZoneId.of("Asia/Tokyo"));
String s = formatter.format(t);
時間の切り捨て
Instant t = Instant.now().truncatedTo(ChronoUnit.DAYS); // InstantはUTCの00:00:00
月の演算 (加算など)
LocalDateTime t = LocalDateTime.parse("2022-01-31T00:00:00");
LocalDateTime t2 = t.plusMonths(1); // 2022-02-28T00:00:00
LocalDateTime t = LocalDateTime.parse("2022-02-15T00:00:00");
LocalDateTime t2 = t.with(TemporalAdjusters.lastDayOfMonth()); // 2022-02-28T00:00:00
月日数の取得
LocalDate d = LocalDate.parse("2022-01-01");
int daysInMonth = YearMonth.from(d).lengthOfMonth();
ファイル
文字コード
Charset utf8 = StandardCharsets.UTF_8; // UTF-8
//Charset utf8 = Charset.forName("UTF-8"); // UTF-8 (上と同じ)
Charset sjis = Charset.forName("Shift_JIS"); // Shift_JIS (拡張文字なし)
Charset win31j = Charset.forName("Windows-31J"); // Shift_JIS + 拡張文字 (髙など)
Charset ms932 = Charset.forName("MS932"); // 〃
パス
Path path1 = Path.of("/dir/file.txt");
File file1 = path1.toFile();
Path dirPath = path1.getParent(); // /dir
Path fileName = path1.getFileName(); // file.txt
Path path2 = dirPath.resolve("file2.txt"); // /dir/file2.txt
Path path3 = path1.resolveSibling("file3.txt"); // /dir/file3.txt
読み込み
try {
Path path = Path.of("/tmp/test.txt");
List<String> lines = Files.readAllLines(path, Charset.forName("Windows-31j"));
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
Path path = Path.of("/tmp/test.txt");
try (FileReader fr = new FileReader(path.toFile(), Charset.forName("Windows-31j"));
BufferedReader br = new BufferedReader(fr)) {
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
書き込み
try {
Path path = Path.of("/dir/sub/sub2/test.txt");
Path dirPath = path.getParent();
if (!Files.exists(dirPath)) {
Files.createDirectories(dirPath);
}
Files.writeString(path, "あいう", Charset.forName("Windows-31j"));
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
Path path = Path.of("/tmp/test.txt");
try (BufferedWriter bw = Files.newBufferedWriter(path, Charset.forName("UTF-8"))) {
bw.write('\ufeff');
bw.write("あいう");
}
} catch (IOException e) {
throw new RuntimeException(e);
}
JSON (Jackson)
パース
try {
String json = "{\"items\": [{\"name\": \"item1\"}]}";
var map = new ObjectMapper().readValue(json, new TypeReference<Map<String, Object>>() {});
} catch (IOException e) {
throw new RuntimeException(e);
}
文字列化
try {
var map = Map.of("items", List.of(Map.of("name", "item1")));
String json = new ObjectMapper().writeValueAsString(map); // {"items":[{"name":"item1"}]}
// String json = new ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(map); // インデント付
} catch (IOException e) {
throw new RuntimeException(e);
}