Google Guava学习笔记guava

Getting Started With Google Guav

2016-08-24  本文已影响476人  Viking_Den

使用Joiner

典型的使用原生的java处理拼接字符串的方法:

    public String buildString(List<String> stringList, String delimiter){
         StringBuilder builder = new StringBuilder();
         for (String s : stringList) {
             if(s !=null){
                 builder.append(s).append(delimiter);
             }
        }
        builder.setLength(builder.length() – delimiter.length());
        return builder.toString();
   }

注意:这里需要移除最后一个分隔符。
原生的java实现其实也不是很复杂,但是使用Google Guava类库中的Joiner来实现的话更加简洁:

    Joiner.on("|").skipNulls().join(stringList);

上面的skipNulls方法是忽略了stringList中为null的空值。当然,Joiner中也可以指定空值得替代,比如如下的代码:

     Joiner.on("|").useForNull("no value").join(stringList);

有几点需要说明:Joiner类不仅能处理String类型的数据,还能处理数组,迭代对象以及任何对象的可变参数类。其实也是调用了Object的toString()方法。另外如果空值存在集合中,并且skipNulls活着useForNull都没有指定的话,NullPointerException异常将会抛出。还有,一旦Joiner对象创建,将会是不变的。比如如下的useForNull将不会起任何作用:

     Joiner stringJoiner = Joiner.on("|").skipNulls();
     //the useForNull() method returns a new instance of the Joiner!
     stringJoiner.useForNull("missing");
     stringJoiner.join("foo","bar",null);

Joiner类不仅可以返回String对象,还可以返回StringBuilder对象:

      StringBuilder stringBuilder = new StringBuilder();
      Joiner joiner = Joiner.on("|").skipNulls();
     //returns the StringBuilder instance with the values foo,bar,baz appeneded with "|" delimiters
     joiner.appendTo(stringBuilder,"foo","bar","baz")

Joiner类可以作用于实现了Appendable的所有类:

     FileWriter fileWriter = new FileWriter(new File("path")):
     List<Date> dateList = getDates();
     Joiner joiner = Joiner.on("#").useForNulls(" ");
     //returns the FileWriter instance with the valuesappended into it
     joiner.appendTo(fileWriter,dateList);

Joiner类也可以作用于Map对象:

    public void testMapJoiner() {
         //Using LinkedHashMap so that the original order is preserved
         String expectedString = "Washington D.C=Redskins#New York City=Giants#Philadelphia=Eagles#Dallas=Cowboys";
         Map<String,String> testMap = Maps.newLinkedHashMap();
         testMap.put("Washington D.C","Redskins");
         testMap.put("New York City","Giants");
         testMap.put("Philadelphia","Eagles");
         testMap.put("Dallas","Cowboys");
         String returnedString = Joiner.on("#").withKeyValueSeparator("=").join(testMap);
         assertThat(returnedString,is(expectedString));
    }
上一篇下一篇

猜你喜欢

热点阅读