#Ref. site
#メソッド参照
-https://www.sejuku.net/blog/22337
#■■■関数型interfaceの実装をラムダ式に置き換え
関数型インターフェースとは抽象メソッドを1つだけ持つインターフェースのことです。
■匿名クラスでの記述(従来例)
// インターフェース
interface InterfaceTest{
// 抽象メソッド
public String method(String name, int n);
}
public class Main {
public static void main(String[] args) {
// 匿名クラスの場合
InterfaceTest it = new InterfaceTest() {
// オーバーライド
public String method(String name, int n) {
return "Hello " + name + n + "!";
}
};
System.out.println(it.method("Java", 8));
}
}
Result
Hello Java8!
■ラムダ式での記述
// インターフェース
interface InterfaceTest{
// 抽象メソッド
public String method(String name, int n);
}
public class Main {
public static void main(String[] args) {
// ラムダ式の場合
InterfaceTest it = (name, n) -> {
return "Hello " + name + n + "!";
};
System.out.println(it.method("Java", 8));
}
}
Result
Hello Java8!
#■String to LocalDateTime
String dateString = '20201112131415';
String dateString = '20201112';
LocalDateTime dateTime = (dateString.length() > 8)
? LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("yyyyMMddHHmmss"))
: LocalDate.parse(dateString, DateTimeFormatter.ofPattern("yyyyMMdd")).atTime(LocalTime.MIN);
#■LocalDateTime to String
LocalDateTime dateTime = LocalDateTime.of(2020, 11, 12, 13, 14, 15);
String dateString = dateTime.format("yyyy/MM/dd HH:mm:ss");
#■LocalDateTime to LocalDate
LocalDateTime dateTime = LocalDateTime.of(2020, 1, 2, 3,4 ,5);
LocalDate date = date.toLocalDate();
#■String
System.out.println("--------------- ■replace ---------------");
String str = "aaa-bbb-ccc";
System.out.println(str.replace("-", "")); // aaabbbccc
System.out.println(str); // aaa-bbb-ccc
System.out.println("--------------- ■subString ---------------");
String str = "123456789";
System.out.println(str.substring(1, 5));// 2345
System.out.println(str); // 123456789
System.out.println("--------------- ■getLastChar ---------------");
String str = "1234567890";
System.out.println(str.substring(str.length() - 8));// [34567890]
System.out.println(str); // [1234567890]
System.out.println("--------------- ■stripLeading ---------------");
String str = " 123456789 ";
System.out.println(str.stripLeading() + "End");// [123456789 End]
System.out.println(str); // [ 123456789 ]
#■enum
public class enumTest {
public static void main(String[] args) {
getKeyValue();
}
private static void getKeyValue() {
String[] msgList = {"e0001", "e0002"};
for (String id : msgList) {
System.out.println(MessageEnum.valueOf(id)); // e0001
System.out.println(MessageEnum.valueOf(id).getMessage()); // メッセージ
}
}
enum MessageEnum {
e0001("メッセージ"),
e0002("メッセージ222");
private final String message;
public String getMessage(){
return message;
}
MessageEnum(String message) {
this.message = message;
}
}
}
//************************ Result
e0001
メッセージ
e0002
メッセージ222
#■LocalDate, LocalDateTimeテスト結果
private static void checkDisplay() {
System.out.println("************************ checkDisplay ******************************");
System.out.println(LocalDate.of(2020,1,1));
System.out.println(LocalDate.of(2020,1,1)); // 2020-01-01
System.out.println(LocalDateTime.of(2020,1,1,1,1,1).toString());//2020-01-01T01:01:01
/*
2020-01-01
2020-01-01
2020-01-01T01:01:01
*/
}
public static LocalDate convert(String date, String formatter) {
return LocalDate.parse(date, DateTimeFormatter.ofPattern(formatter));
}
public static LocalDateTime convertLocalDateTime(String date, String formatter) {
if (date.length() <= 10) {
LocalDate noTimestamp = convert(date, formatter.replaceAll(" ", "").split("HH", 0)[0]);
return (noTimestamp != null) ? noTimestamp.atTime(LocalTime.MIN) : null;
}
return LocalDateTime.parse(date, DateTimeFormatter.ofPattern(formatter));
}
private static String stringToDateWithFormat(String value, String format) {
// LocalDateTime型に変更
LocalDateTime dateValue = LocalDateTime.parse((value.length() > 8) ? value : value.concat("000000"), DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
return dateValue.format(DateTimeFormatter.ofPattern(format));
}
private static void before() {
System.out.println("************************ before ******************************");
LocalDate date1 = LocalDate.of(2020,1,1);
LocalDate date2 = LocalDate.of(2020,1,1);
LocalDate date3 = LocalDate.of(2020,1,2);
System.out.println(date1.isAfter(date2)); // false
System.out.println(date1.isAfter(date3)); // false
System.out.println(date3.isAfter(date2)); // true
}
private static void stringToDate() {
System.out.println("************************ stringToDate ******************************");
System.out.println(stringToDateWithFormat("20200102", "yyyy/MM/dd HH:mm")); // 2020/01/02 00:00
System.out.println(stringToDateWithFormat("20200102", "yyyy/MM/dd")); // 2020/01/02
System.out.println(stringToDateWithFormat("20200102", "MM/dd HH:mm")); // 01/02 00:00
System.out.println(stringToDateWithFormat("20200102", "HH:mm")); // 00:00
System.out.println(stringToDateWithFormat("20200102030405", "yyyy/MM/dd HH:mm")); // 2020/01/02 03:04
System.out.println(stringToDateWithFormat("20200102030405", "yyyy/MM/dd")); // 2020/01/02
System.out.println(stringToDateWithFormat("20200102030405", "MM/dd HH:mm")); // 01/02 03:04
System.out.println(stringToDateWithFormat("20200102030405", "HH:mm")); // 03:04
// Error because of count > 14
// System.out.println(stringToDateWithFormat("202001020303059999", "yyyy/MM/dd HH:mm"));
// System.out.println(stringToDateWithFormat("202001020303059999", "yyyy/MM/dd"));
// System.out.println(stringToDateWithFormat("202001020303059999", "MM/dd HH:mm"));
// System.out.println(stringToDateWithFormat("202001020303059999", "HH:mm"));
/*
************************ stringToDate ******************************
2020/01/02 00:00
2020/01/02
01/02 00:00
00:00
2020/01/02 03:04
2020/01/02
01/02 03:04
03:04
Exception in thread "main" java.time.format.DateTimeParseException: Text '202001020303059999' could not be parsed at index 0
at java.base/java.time.format.DateTimeFormatter.parseResolved0(DateTimeFormatter.java:2046)
at java.base/java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1948)
at java.base/java.time.LocalDateTime.parse(LocalDateTime.java:492)
at Date.Date.stringToDateWithFormat(Date.java:33)
at Date.Date.stringToDate(Date.java:51)
at Date.Date.main(Date.java:14)
*/
}
private static void localDateTimeTolocalDate() {
System.out.println("************************ localDateTimeTolocalDate ******************************");
LocalDateTime date = LocalDateTime.of(2020, 1, 2, 3,4 ,5);
System.out.println("LocalDateTime =" + date); // LocalDateTime =2020-01-02T03:04:05
System.out.println("LocalDateTime -> LocalDate =" + date.toLocalDate()); // LocalDateTime -> LocalDate =2020-01-02
}
private static void localDateToString() {
System.out.println("************************ localDateToString ******************************");
LocalDate date = LocalDate.of(2020, 1, 2);
System.out.println("LocalDate =" + date);
System.out.println("LocalDate -> String =" + date.toString());
System.out.println("LocalDate -> String(Without -) =" + date.toString().replace("-", ""));
/*
************************ localDateToString ******************************
LocalDate =2020-01-02
LocalDate -> String =2020-01-02
LocalDate -> String(Without -) =20200102
*/
}
private static void localDatePlusDay() {
System.out.println("************************ localDatePlusDay ******************************");
Short plusValue = 2;
LocalDate date = LocalDate.of(2020, 1, 2);
System.out.println("LocalDate =" + date);
System.out.println("LocalDate -> String =" + date.toString());
System.out.println("LocalDate -> String(Without -) =" + date.toString().replace("-", ""));
System.out.println("LocalDate(plusDays:" + plusValue + ") =" + date.plusDays(plusValue));
/*
************************ localDatePlusDay ******************************
LocalDate =2020-01-02
LocalDate -> String =2020-01-02
LocalDate -> String(Without -) =20200102
LocalDate(plusDays:2) =2020-01-04
*/
}
private static String localDateTimeToString(LocalDateTime paramDate, String paramFormat) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(paramFormat);
return paramDate.format(formatter);
}
private static String localDateToStringWithFormat(LocalDate paramDate, String paramFormat) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(paramFormat);
return paramFormat.contains("HH:mm") ? paramDate.atTime(LocalTime.MIN).format(formatter) : paramDate.format(formatter);
}
private static void test1() {
System.out.println("************************ test1 ******************************");
System.out.println("■String to Date:" + convertLocalDateTime("2020/10/11 11:22", "yyyy/MM/dd HH:mm")); // ■String to Date:2020-10-11T11:22
System.out.println("■String to Date:" + convertLocalDateTime("2020/10/11 11:22", "yyyy/MM/dd HH:mm")); // ■String to Date:2020-10-11T11:22
System.out.println("■LocalDateTime to String(yyyy/MM/dd):" + localDateTimeToString(LocalDateTime.now(), "yyyy/MM/dd")); // ■LocalDateTime to String(yyyy/MM/dd):2020/06/09
System.out.println("■LocalDateTime to String(yyyy/MM/dd HH:mm):" + localDateTimeToString(LocalDateTime.of(2020,12,12,0,1,2), "yyyy/MM/dd HH:mm")); // ■LocalDateTime to String(yyyy/MM/dd HH:mm):2020/12/12 00:01
System.out.println("■LocalDateTime to String(yyyy/MM/dd HH:mm):" + localDateTimeToString(LocalDateTime.of(2020,12,12,23,1,2), "yyyy/MM/dd HH:mm")); // ■LocalDateTime to String(yyyy/MM/dd HH:mm):2020/12/12 23:01
System.out.println("■LocalDateTime to String(yyyy/MM/dd hh:mm):" + localDateTimeToString(LocalDateTime.of(2020,12,12,0,1,2), "yyyy/MM/dd hh:mm")); // ■LocalDateTime to String(yyyy/MM/dd hh:mm):2020/12/12 12:01
System.out.println("■LocalDateTime to String(yyyy/MM/dd hh:mm):" + localDateTimeToString(LocalDateTime.of(2020,12,12,1,1,2), "yyyy/MM/dd hh:mm")); // ■LocalDateTime to String(yyyy/MM/dd hh:mm):2020/12/12 01:01
System.out.println("■LocalDateTime to String(yyyy/MM/dd hh:mm):" + localDateTimeToString(LocalDateTime.of(2020,12,12,14,1,2), "yyyy/MM/dd hh:mm")); // ■LocalDateTime to String(yyyy/MM/dd hh:mm):2020/12/12 02:01
System.out.println("■LocalDateTime to String(yyyy/MM/dd hh:mm):" + localDateTimeToString(LocalDateTime.now(), "yyyy/MM/dd hh:mm")); // ■LocalDateTime to String(yyyy/MM/dd hh:mm):2020/06/09 05:53
System.out.println("■LocalDateTime to String(yyyy/MM/dd HH24:mm):" + localDateTimeToString(LocalDateTime.now(), "yyyy/MM/dd HH24:mm")); // ■LocalDateTime to String(yyyy/MM/dd HH24:mm):2020/06/09 1724:53
System.out.println("■LocalDateTime to String(MM/dd):" + localDateTimeToString(LocalDateTime.now(), "MM/dd")); // ■LocalDateTime to String(MM/dd):06/09
System.out.println("■LocalDate to String(yyyy/MM/dd):" + localDateToStringWithFormat(LocalDate.now(), "yyyy/MM/dd")); // ■LocalDate to String(yyyy/MM/dd):2020/06/09
System.out.println("■LocalDate to String(MM/dd):" + localDateToStringWithFormat(LocalDate.now(), "MM/dd")); // ■LocalDate to String(MM/dd):06/09
System.out.println("■LocalDate to String(yyyy/MM/dd HH:mm):" + localDateToStringWithFormat(LocalDate.now(), "yyyy/MM/dd HH:mm")); // ■LocalDate to String(yyyy/MM/dd HH:mm):2020/06/09 00:00
System.out.println("■LocalDate to String(MM/dd HH:mm):" + localDateToStringWithFormat(LocalDate.now(), "MM/dd HH:mm")); // ■LocalDate to String(MM/dd HH:mm):06/09 00:00
/* Result:
■String to Date:2020-10-11T11:22
■LocalDateTime to String(yyyy/MM/dd):2020/03/31
■LocalDateTime to String(yyyy/MM/dd HH:mm):2020/12/12 00:01
■LocalDateTime to String(yyyy/MM/dd HH:mm):2020/12/12 23:01
■LocalDateTime to String(yyyy/MM/dd hh:mm):2020/12/12 12:01
■LocalDateTime to String(yyyy/MM/dd hh:mm):2020/12/12 01:01
■LocalDateTime to String(yyyy/MM/dd hh:mm):2020/12/12 02:01
■LocalDateTime to String(yyyy/MM/dd hh:mm):2020/03/31 03:50
■LocalDateTime to String(yyyy/MM/dd HH24:mm):2020/03/31 1524:50
■LocalDateTime to String(MM/dd):03/31
■LocalDate to String(yyyy/MM/dd):2020/03/31
■LocalDate to String(MM/dd):03/31
■LocalDate to String(yyyy/MM/dd HH:mm):2020/03/31 00:00
■LocalDate to String(MM/dd HH:mm):03/31 00:00
*/
}
■タイムアウトテスト
public class TimeUnit {
public static void main(String[] args) throws InterruptedException {
timeUnit();
calculateTime();
}
private static void calculateTime() throws InterruptedException {
Integer period = 10;
long now;
long start = System.currentTimeMillis();
for (int i = 1; i <= 2; i++) {
now = System.currentTimeMillis();
if (now - start > period) {
System.out.println("タイムアウトしました");
break;
}
executeProcess();
}
}
private static void executeProcess() throws InterruptedException {
System.out.println("****************** Execution Start ******************");
java.util.concurrent.TimeUnit.MILLISECONDS.sleep(100);
System.out.println("****************** Execution End");
}
private static void timeUnit() throws InterruptedException {
System.out.println(java.util.concurrent.TimeUnit.MILLISECONDS + ", value=" + System.currentTimeMillis());
java.util.concurrent.TimeUnit.MILLISECONDS.sleep(10000);
System.out.println(java.util.concurrent.TimeUnit.MILLISECONDS + ", value=" + System.currentTimeMillis());
System.out.println(java.util.concurrent.TimeUnit.MICROSECONDS);
System.out.println(java.util.concurrent.TimeUnit.NANOSECONDS);
System.out.println(java.util.concurrent.TimeUnit.DAYS);
System.out.println(java.util.concurrent.TimeUnit.HOURS);
System.out.println(java.util.concurrent.TimeUnit.MINUTES);
System.out.println(java.util.concurrent.TimeUnit.SECONDS);
}
}
//*********************************** Result ******************************* //
MILLISECONDS, value=1599635237478
MILLISECONDS, value=1599635247541
MICROSECONDS
NANOSECONDS
DAYS
HOURS
MINUTES
SECONDS
****************** Execution Start ******************
****************** Execution End
タイムアウトしました
#■Map Search
private static Map<String, String> MAP = Map.of(
"001", "01",
"002", "02",
"003", "03");
public static void main(String[] args) {
search("001"); // 01
search("002"); // 02
search("003"); // 03
search("006"); // null
}
private static void search(String value) {
System.out.println(MAP.get(value));
}
#■Static, Inner Class {}
public class StaticTest {
static {
System.out.println("Static.....");
}
public static void main(String[] args) {
staticTest();
innerTest();
}
private static void staticTest() {
System.out.println("staticTest Method");
}
private static void innerTest() {
innerClassT obj = new innerClassT();
System.out.println(obj.getTest());
}
static class innerClassT {
{
test = "{} setting";
System.out.println("innerClassT Static.....");
}
private String test;
public String getTest() {
return test;
}
}
}
********************* Result:
Static.....
staticTest Method
innerClassT Static.....
{} setting
#stream (Object)
import static java.util.Objects.nonNull;
import java.util.ArrayList;
import java.util.List;
public class Stream {
public static void main(String[] args) {
MyObject obj1 = new MyObject();
obj1.str = "1st";
obj1.intVal = 100;
MyObject obj2 = new MyObject();
obj2.str = "2nd";
obj2.intVal = 200;
List<MyObject> lst = new ArrayList<MyObject>();
lst.add(obj1);
lst.add(obj2);
streamIsExists(lst);
}
private static void streamIsExists(List<MyObject> lst) {
System.out.println("'xxx' exist in lst list : Result = " + isExist(lst, "xxx"));
System.out.println("'1st' exist in lst list : Result = " + isExist(lst, "1st"));
System.out.println("'1st' exist in lst list : Result = " + isExist(lst, "GG"));
}
private static boolean isExist(List<MyObject> lst, String searchVal) {
return lst.stream()
.filter(MyObject -> nonNull(MyObject.str))
.filter(MyObject -> searchVal.equals(MyObject.str))
.findFirst()
.isPresent();
}
}
class MyObject {
String str;
int intVal;
}
/* ********************* Result
'xxx' exist in lst list : Result = false
'1st' exist in lst list : Result = true
'1st' exist in lst list : Result = false
*/
#stream (Object Filter)
import static java.util.Objects.isNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
public class Stream_ObjFilter {
public static void main(String[] args) {
filter();
}
private static void filter() {
System.out.println("'1st' exist in lst list : Result = " + getInnerClassValObj(getList("1st")).isPresent());
System.out.println("'1st' exist in lst list : Result = " + getInnerClassValObj(getList("2nd")).isPresent());
}
private static List<MyObject3> getList(String strVal) {
MyObject3 obj1 = new MyObject3();
obj1.intVal = 100;
MyObject3 obj2 = new MyObject3();
obj2.classVar = new InnerClass();
obj2.classVar.str = strVal;
obj2.intVal = 100;
List<MyObject3> lst = new ArrayList<MyObject3>();
lst.add(obj1);
lst.add(obj2);
return lst;
}
private static Optional<InnerClass> getInnerClassValObj(List<MyObject3> lst) {
return lst.stream()
.filter(InnerClass::hasValue)
.map(MyObject3::getInnerClass)
.filter(Objects::nonNull)
.filter(InnerClass::isFirst)
.findAny();
}
}
class MyObject3 {
InnerClass classVar;
int intVal;
public InnerClass getInnerClass() {
return this.classVar;
}
}
class InnerClass {
String str;
public static boolean hasValue(MyObject3 myObject3) {
return !isNull(myObject3.toString());
}
public boolean isFirst() {
return "1st".equals(this.str);
}
}
/* ********************* Result
'1st' exist in lst list : Result = true
'1st' exist in lst list : Result = false
*/
#instanceof
private static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}