guava 拼接字符串 List&Map


    private final List<String> stringList= Arrays.asList(
            "a","b","c"
    );
    private final List<String> stringList2= Arrays.asList(
            "a","b","c",null
    );

    private final Map<String,String> stringMap=of("hello","Guava","Java","Scala");

    private final String targetFilepath="D:\\BaiduNetdiskDownload\\guava-joioner.txt";




    @Test
    public void testJoinerOnJoiner(){
        String result = Joiner.on("#").join(stringList);
        assertThat(result,equalTo("a#b"));
    }


    @Test
    public void testJoinerOnJoiner2(){
        String result = Joiner.on("#").join(stringList2);
        assertThat(result,equalTo("a#b"));
    }

    @Test
    public void testJoinerOnJoiner3(){
        String result = Joiner.on("#").skipNulls().join(stringList2);
        assertThat(result,equalTo("a#b#c"));
    }


    @Test
    public void testJoinerOnJoiner4(){
        String result = Joiner.on("#").useForNull("d").join(stringList2);
        assertThat(result,equalTo("a#b#c#d"));
    }


    @Test
    public void testJoinerOnJoiner5(){
        final StringBuilder builder=new StringBuilder();
        StringBuilder result = Joiner.on("#").useForNull("d").appendTo(builder,stringList2);
        assertThat(builder,sameInstance(result));
    }


    @Test
    public void testJoinerOnappendtowriter() throws IOException {
        FileWriter fileWriter=null;
        try{
            fileWriter=new FileWriter(new File(targetFilepath));
            Joiner.on("#").useForNull("d").appendTo(fileWriter, stringList2);
            fileWriter.flush();
        }catch (IOException e){
            fail("append to the writer occur fetal error.");
        }finally {
            fileWriter.close();
        }
    }



    @Test
    public void testJoinerOnappendtowriter1() throws IOException {
        String collect = stringList2.stream().filter(item -> item != null && !item.isEmpty()).collect(Collectors.joining("#"));
        System.out.println(collect);
    }

    @Test
    public void testJoinerOnappendtowriter2() throws IOException {
        String collect = stringList2.stream().map(item->item==null||item.isEmpty()?"d":item).collect(Collectors.joining("#"));
        System.out.println(collect);
    }

    @Test
    public void testJoinerMap() throws IOException {
        String join = Joiner.on("#").withKeyValueSeparator("=").join(stringMap);
        System.out.println(join);


    }

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值