[Java] 介面CharSequence在Java 8的預設實作方法: chars(), codePoints()

在Java 8,介面(Interface)可以有預設的實作方法(default method)。

預設方法使用default關鍵字修飾,預設權限為public。

介面CharSequence在Java 8新增了預設方法chars(), codePoints(),主要用來處理字元和字元的碼位(code point)。

chars(), codePoints()皆輸出IntStream物件,物件內元素紀錄字元串。

 

CharSequence類別的Unicode字元處理方法: chars, codePoints

Java主要使用Unicode編碼系統。Unicode對文字和符號進行編碼,可用碼位表示字元,經過轉換即可呈現我們一般所看到的文字。

以大寫拉丁字母S為例,碼位為83。其餘文字的轉換表可參考這裡

 

default IntStream chars()
Return an IntStream of char values from this sequence.
default IntStream codePoints()
Return an IntStream of Unicode code points from this sequence.

基本上chars & codePoints的用法差不多,沒有太大差異。

 

CharSequence類別的chars & codePoints方法的實作練習

import java.util.stream.IntStream;
import java.util.stream.Stream;

public class CharSequenceDemo {

    public static void main(String[] args) {

        //Conversion Using chars()
        String testString = "String";
        IntStream intStream = testString.chars(); // 產生一個IntStream的物件,裡面包含’S’, ’t’, ’r’, ‘i’, ’n’, ‘g’的碼位:83 116 114 105 110 103
        intStream.forEach(n -> System.out.print(n + " "));
        System.out.println();

        Stream<Character> characterStream = testString.chars()
                .mapToObj(c -> (char) c); // 產生一個Stream<Character>的物件,裡面包含’S’, ’t’, ’r’, ‘i’, ’n’, ‘g'
        characterStream.forEach(n -> System.out.print(n + " "));
        System.out.println();

        
        //Conversion Using codePoints()
        IntStream intStream1 = testString.codePoints();
        intStream1.forEach(n -> System.out.print(n + " "));
        System.out.println();

        Stream<Character> characterStream2
                = intStream1.mapToObj(c -> (char) c);
        characterStream2.forEach(n -> System.out.print(n + " "));
        System.out.println();


        //Conversion to a Stream of Single Character Strings
        Stream<String> stringStream = testString.codePoints()
                .mapToObj(c -> String.valueOf((char) c));
        stringStream.forEach(n -> System.out.print(n + " "));


    }
}

 

輸出

83 116 114 105 110 103 
S t r i n g
83 116 114 105 110 103
S t r i n g
S t r i n g

 

<U> Stream<U> mapToObj(IntFunction mapper)
Returns an object-valued Stream consisting of the results of applying the given function to the elements of this stream.
This is an
intermediate operation(中間操作).