Guava学习笔记--01. Joiner使用

对于Guava的认识来自于阅读QMQ源码的时候,有很多没有使用过的Java方法和集合,所以就查了查,发现是用的是Guava的类库,所以就有了下面的博客:

1. 字符串的拼接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
private final List<String> stringList = Arrays.asList("Google", "Guava", "Java", "Scala", "Kafka");
private final List<String> stringListWithNullValue = Arrays.asList("Google", "Guava", "Java", "Scala", null);


//1. 字符串的拼接
@Test
public void Test() {
String join = Joiner.on("*").join(stringList);
System.out.println(join);
assertEquals(join, "Google*Guava*Java*Scala*Kafka");
}

@Test(expected = NullPointerException.class)
public void TestJoinValue() {
String join = Joiner.on("*").join(stringListWithNullValue);
System.out.println(join);
assertEquals(join, "Google*Guava*Java*Scala*Kafka");
}
```
#### 2. 跳过空数据
``` java
//2. 跳过空数据
@Test
public void TestJoinSkipValue() {
String join = Joiner.on("*").skipNulls().join(stringListWithNullValue);
System.out.println(join);
assertEquals(join, "Google*Guava*Java*Scala");
}
```
#### 3. 为空的数据指定一个默认值
``` java
//3. 为空的数据指定一个默认值
@Test
public void TestJoinDefalutValue() {
String join = Joiner.on("*").useForNull("Defalut").join(stringListWithNullValue);
System.out.println(join);
assertEquals(join, "Google*Guava*Java*Scala*Defalut");
}

4. 追加到StringBuilder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
    //4. 追加到StringBuilder
@Test
public void TestJoinDefalutValueStringBuffer() {
StringBuilder stringBuilder = new StringBuilder();
StringBuilder thatBuilder = Joiner.on("*").useForNull("Defalut").appendTo(stringBuilder, stringListWithNullValue);
assertThat(thatBuilder, sameInstance(stringBuilder));
assertThat(stringBuilder.toString(), equalTo("Google*Guava*Java*Scala*Defalut"));
assertThat(thatBuilder.toString(), equalTo("Google*Guava*Java*Scala*Defalut"));
}
```

#### 5. 追加到文件
``` java
//5. 追加到文件
@Test
public void TestJoinDefalutValueToWrite() {

try (FileWriter fileWriter = new FileWriter(new File("1.txt"))) {
Joiner.on("#").useForNull("Default").appendTo(fileWriter, stringListWithNullValue);
assert (Files.isFile().test(new File("1.txt")));
} catch (IOException e) {
e.printStackTrace();
}
}

6. 使用Java8实现相同的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    //java8
@Test
public void TestJoinDefalutByStream() {
String result = stringListWithNullValue.stream().map(x -> x == null || x.isEmpty() ? "Defalut" : x).collect(Collectors.joining("*"));
assertThat(result, equalTo("Google*Guava*Java*Scala*Defalut"));
}
```
#### 7. 使用Guava对Map进行join
``` java
@Test
public void testJoinOnWithMap(){
//创建一个map
Map<String,String> stringMap= ImmutableMap.of("Hello","Guava","Java","Scala");
String join = Joiner.on("#").withKeyValueSeparator("=").join(stringMap);
System.out.println(join);
assert join.equals("Hello=Guava#Java=Scala");
}

阅读更多