java中Joiner的使用笔记

时间:2025-02-21 07:44:25

需要的jar包地址

		<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>

1. 将一个list进行分隔,输出一个字符串

List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
        String str = Joiner.on(":").join(list);
        System.out.println(str);

输出结果

AA:BB:CC:BB:CC:AA:AA

2. 过滤出里面的null值

List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA", null);
        String str = Joiner.on(":").skipNulls().join(list);
        System.out.println(str);

输出结果

AA:BB:CC:BB:CC:AA:AA

3.将里面的null值进行替换

AA:BB:CC:BB:CC:AA:AA:!

4.使用流的方式进行字符串分隔输出

 List<String> list = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA", null);
        String str = list.stream().collect(Collectors.joining(";"));
        System.out.println(str);

输出结果

AA;BB;CC;BB;CC;AA;AA;null

5.将Map分隔

 Map<String, Object> map = new HashMap<>();
        map.put("name", "zhangsan");
        map.put("age", "23");
        String join = Joiner.on(",").withKeyValueSeparator("=").join(map);
        System.out.println(join);

输出结果

name=zhangsan,age=23