GuavaJoiner、Splitter使用

编程

1、List转String

public static List<String> strings = Arrays.asList("test1","test2","test3");

@Test

public void test3(){

String str = Joiner.on(",").join(strings);

System.out.println(str);

}

结果:

test1,test2,test3

2、String转List

public static String str = "test1,test2,test3";

@Test

public void test4(){

List<String> platforms = Splitter.on(",").trimResults().splitToList(str);

System.out.println(platforms);

}

结果:

[test1, test2, test3]

3、useForNull替换null值

public static List<String> stringList = Arrays.asList("test1",null,"test3");

@Test

public void test5(){

String result = Joiner.on(",").useForNull("null").join(stringList);

System.out.println(result);

}

结果:

test1,null,test3

4、skipNulls跳过null值

public static List<String> stringList = Arrays.asList("test1",null,"test3");

@Test

public void test5(){

String result = Joiner.on(",").skipNulls().join(stringList);

System.out.println(result);

}

结果:

test1,test3

5、appendTo

它的功能是可以把集合转成StringBuilder或者StringBuffer

public static List<String> stringList = Arrays.asList("test1","test2","test3");

@Test

public void test5(){

StringBuilder result = Joiner.on(",").appendTo(new StringBuilder(), stringList);

System.out.println(result);

}

6、Splitter用途

@Test

public void test4(){

String str = "test1,test2,, test4,";

// 只切割转换List

Splitter.on(",").split(str).forEach(System.out::println);

System.out.println("----");

// 切割字符串转List,去掉空值

Splitter.on(",").omitEmptyStrings().split(str).forEach(System.out::println);

System.out.println("----");

// 切割字符串转List,去掉空值,去掉空格

Splitter.on(",").omitEmptyStrings().trimResults().split(str).forEach(System.out::println);

// 固定长度分割 fixedLength

System.out.println("----");

Splitter.on(",").fixedLength(5).split(str).forEach(System.out::println);

// 指定长度分割

System.out.println("----");

Splitter.on(",").limit(2).split(str).forEach(System.out::println);

// 转Map

System.out.println("----");

String new_str = "1:haha,2:hehe";

Map<String,String> map = Splitter.on(",").withKeyValueSeparator(":").split(new_str);

System.out.println(map.get("1"));

}

7、差集、并集、交集

@Test

public void test3(){

Set<String> set1 = new HashSet<>();

set1.add("set1");

Set<String> set2 = new HashSet<>();

set2.add("set2");

set2.add("uuu");

// 求差集,set2与set1之间的差集

Sets.SetView<String> difference = Sets.difference(set2,set1);

System.out.println(difference);

// intersection 交集

// union 并集

}

以上是 GuavaJoiner、Splitter使用 的全部内容, 来源链接: utcz.com/z/517312.html

回到顶部