Guava学习:Joiner和Splitter工具(二)
测试类:
package com.example.demo; import java.util.Arrays; import java.util.List; import org.assertj.core.internal.Characters; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import com.google.common.collect.Lists; import com.google.common.primitives.Booleans; import com.google.common.primitives.Chars; import com.google.common.primitives.Doubles; import com.google.common.primitives.Floats; import com.google.common.primitives.Ints; /** * @author zero 2019/02/23 */ public class GuavaExample { public static void main(String[] args) { System.out.println("Guava excesice."); // testGuavaCommonUseMethod(); // testGuavaSplitterAllTypeMethod(); testGuavaJoinerAllTypeMethod(); } // 测试1:初步 public static void testGuavaCommonUseMethod() { String string = "a,bb,ccc,dddd"; String[] strings = {"a", "b", "c"}; // 数组需要进行转换成list集合比较安全,当然也可以直接join String newStrings = Joiner.on("-").join(Arrays.asList(strings)); System.out.println(newStrings); Iterable<String> newString2 = Splitter.on(",").split(string); newString2.forEach(System.out::println); System.out.println(newString2); } // Test Splitter Method public static void testGuavaSplitterAllTypeMethod() { String string = "apple,xiaomi,,,honour,,vivo-nex"; String string2 = "1-2-3-4-5-6"; // 去掉无用的值 Iterable<String> usefulString = Splitter.on(",").omitEmptyStrings().trimResults().split(string); usefulString.forEach(System.out::println);// apple xiaomi honour vivo-nex // fixedLength(3):表示三个字符三个字符切断促成一个元素。 Iterable<String> newString2 = Splitter.fixedLength(3).split(string2); System.out.println(newString2);// [1-2, -3] newString2.forEach(System.out::println);// 1-2 -3- 4-5 -6 // 遍历字符串的每个字符: 如果含有匹配的字段,则剔除匹配的字段再输出字符;如果没匹配上,则输出元字符。 Iterable<String> patternString = Splitter.onPattern("-").split(string2); System.out.println(patternString);// [1, 2, 3, 4, 5, 6] } // Test Joiner Method public static void testGuavaJoinerAllTypeMethod() { String[] strings = {"a", "b", "c"}; List<Integer> integers = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7); String joinStr = Joiner.on('-').join(integers); System.out.println(joinStr); String joinNewStr = Joiner.on("to").join(integers); System.out.println(joinNewStr); // Guava对基本类型的支持 int[] numbers = {1, 2, 3, 4, 5}; float[] f = {1.0f, 2.00f, 3.000f}; double[] d = {10.00, 20.12, 0.25}; char[] c = {'c', 'd', 'a'}; boolean[] b = {true, false}; String numStr = Joiner.on(";").join(Ints.asList(numbers)); System.out.println(numStr); String newF = Joiner.on(";").join(Floats.asList(f)); System.out.println(newF); String newD = Joiner.on(";").join(Doubles.asList(d)); System.out.println(newD); String newC = Joiner.on(";").join(Chars.asList(c)); System.out.println(newC); String newB = Joiner.on(";").join(Booleans.asList(b)); System.out.println(newB); } }
2.测试结果: