Guava - 字符串處理


Joiner

連接
比如,有這樣一個集合[1,2,3,4,5,7,null],想把這個集合轉換成以#分割的字符串,並過濾掉集合中的空元素

        List<Integer> eleList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, null);
        String joinStr = Joiner.on("#")  //分隔符
                .skipNulls()  //過濾null元素
                .join(eleList);//要分割的集合
        System.out.println(joinStr);

運行結果:1#2#3#4#5#6#7

Splitter

分割
有這樣一個字符串"1,2,3,4,5,6,7",要把這個字符串以,分割,並放到一個集合里面

        String str="1,2,3,4,5,6,7";
        List<String> stringList = Splitter.on(",")
                .trimResults()
                .splitToList(str);
        System.out.println(stringList);

運行結果:[1, 2, 3, 4, 5, 6, 7]

MapJoinner和MapSplitter

主要對url的param的編碼

        Map<String, String> of = ImmutableMap.of("id", "123", "name", "green");
        String join = Joiner.on("&").withKeyValueSeparator("=").join(of);
        System.out.println(join);

運行結果:id=123&name=green

     String str="id=123&name=green";
        Map<String, String> split = Splitter.on("&")
                .withKeyValueSeparator("=")
                .split(str);
        System.out.println(split);

運行結果:{id=123, name=green}


判斷小技巧

Preconditions.checkNotNul(T)//驗證對象是否為null
Preconditions.checkArgument //驗證表達式是否成立


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM