其他分享
首页 > 其他分享> > 05-Joinner

05-Joinner

作者:互联网

单列集合的拼接

 

        List<String> colors = Lists.newArrayList("red", "blue", null, "purple", "yellow", "pink",  null);
        try {
            // 不过滤null,如果有null那么会抛NPE
            String colorStr = Joiner.on(',').join(colors);
            System.out.println(colorStr);
        } catch (NullPointerException e) {
            System.err.println(e);
        }
        // 需要指定如何处理空元素
        // red,blue,purple,yellow,pink
        String colorStr = Joiner.on(',').skipNulls().join(colors);
        System.out.println(colorStr);
        // red,blue,no color,purple,yellow,pink,no color
        String no_color = Joiner.on(',').useForNull("no color").join(colors);
        System.out.println(no_color);

 

双列集合的拼接

 

        Map<String,String> cityDistMap = new HashMap<>();
        cityDistMap.put("海淀区","北京");
        cityDistMap.put("朝阳区",null);
        cityDistMap.put("昌平区","北京");
        //海淀区-北京|朝阳区-北京|昌平区-北京
        try {
            String cityDistMapperStr = Joiner.on("|").withKeyValueSeparator("-").join(cityDistMap);
            System.out.println(cityDistMapperStr);
        }catch (NullPointerException e){
            System.err.println(e);
        }
        try {
            // java.lang.UnsupportedOperationException: can't use .skipNulls() with maps
            String cityDistMapperStr = Joiner.on("|").skipNulls().withKeyValueSeparator("-").join(cityDistMap);
            System.out.println(cityDistMapperStr);
        }catch (UnsupportedOperationException e){
            System.err.println(e);
        }
        // 下面两种方式都OK
        String cityDistMapperStr1 = Joiner.on("|").useForNull("no city").withKeyValueSeparator("-").join(cityDistMap);
        System.out.println(cityDistMapperStr1);
        String cityDistMapperStr2 = Joiner.on("|").withKeyValueSeparator("-").useForNull("no city").join(cityDistMap);
        System.out.println(cityDistMapperStr2);

 

标签:String,05,System,println,Joinner,Joiner,cityDistMap,out
来源: https://www.cnblogs.com/zwy008/p/14826403.html