1. 程式人生 > >Java8新特性一點通 | 回顧字元轉日期&JoinArray使用

Java8新特性一點通 | 回顧字元轉日期&JoinArray使用

StringToDate日期轉換

  • Convert string to date in ISO8601 format

    • 利用LocalDate.parse(CharSequence text) 直接以ISO8601方式格式化
 String originalDate = "2018-08-07";
        LocalDate localDate = LocalDate.parse(originalDate);
        System.out.println("Date:"+localDate);

Output:

Date:2018-08-07
  • Convert string to date in custom formats
    • 利用DateTimeFormatter.ofPattern(String pattern)
      LocalDate.parse(CharSequence text, DateTimeFormatter formatter)結合對日期以指定格式格式化
String originalDate1 = "2018-08-07 10:47:00";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        LocalDate localDate1 = LocalDate.parse(originalDate1,formatter);
        System.out.println("custom date:"
+localDate1); Output: custom date:2018-08-07

Join Array使用

對現有陣列新增字串組成新的字串的幾個方法:
- String.join(CharSequence delimiter, CharSequence… elements) 場景:可以對現有陣列新增分隔符組成新的字串

String joinedString = String.join(",", "hello", "world", "!");
        System.out.println("示例1:" + joinedString);

Output:

示例1
:hello,world,!
  • String.join(CharSequence delimiter, Iterable elements) 場景:可以對現有列表新增分隔符組成新的字串
List<String> strList = Arrays.asList("hello", "world", "!");
        String joinedString1 = String.join(",", strList);
        System.out.println("示例2:" + joinedString1);
Output:

示例2:hello,world,!
  • StringJoiner(CharSequence delimiter) 場景:新增分隔符
 StringJoiner stringJoiner1 = new StringJoiner(",");
        stringJoiner1.add("hello").add("world").add("!");
        System.out.println("示例3:" + stringJoiner1.toString());

Output:

示例3:hello,world,!
  • StringJoiner(CharSequence delimiter, CharSequence prefix, CharSequence suffix) 場景:新增分隔符以及前後綴
StringJoiner stringJoiner2 = new StringJoiner(",", "[", "]");
        stringJoiner2.add("hello").add("world").add("!");
        System.out.println("示例4:" + stringJoiner2.toString());

Output:

示例4:[hello,world,!]
  • Collectors.joining 場景:在lambda表示式裡面用,針對新增分隔符和前後綴的場景
  List<String> strList1 = Arrays.asList("hello", "world", "!");
        String joinedString3 = strList1.stream().collect(Collectors.joining(",","[","]"));
        System.out.println("示例5:"+joinedString3);

Output:

示例5:[hello,world,!]
  • StringUtils.join() 場景:跟以上用法差不多,使用工具類去把資料和列表組成單獨的字串
String[] strArray = {"hello", "world", "!"};
        String joinedString4 = StringUtils.join(strArray, ",");
        System.out.println("示例6:" + joinedString4);

Output:

示例6:hello,world,!