木头人的gravatar头像
木头人 2016-12-30 18:39:32
java项目中使用guava的工具包的心得

   以前只是听过这个工具包,但是真正用的话还是在D75需求中。我要实现把前台传入的list集合用分号分割拼接一个字符串存入数据库,

开始的时候我用代码逻辑如下:

StringBuffer interfaceList=new StringBuffer();

//判断前台绑定中的集合是否为空

if(interfaces!=null)

{

     for(String str:interfaces){

          interfaceList.append(str).append(";");

    }

//去掉最后一个分号

    tpc.setInterfaces(interfacesStr.subStrting(0,interfaceList.length()-1);

}

感觉这里使用了stringbuffer就没问题了吧,然后hery对我说代码还可以压缩,我就看了下apache的StringUtils这个类和google的guava包下

的Joiner这个类。我才发现这样的工具包真的好强大,封装了好多功能,学习是永无止境的。上面的代码只需要写一句就替代了:

String interfacesStr=StringUtils.join(interfaces.iterator(), ';');或者String interfacesStr= Joiner.on(";").join(interfaces.iterator());

有时候我们这样写:

Person person1=new Person("jack",20);

Person person2=new Person("jack",20);

Person person2=new Person("jack",20);

//会去这样存入list集合:

List<Person> personList=new ArrayList<Person>();

personList.add(person1);

personList.add(person2);

personList.add(person3);

在guava中可以这样:List<Person> list = Lists.newArrayList(person1, person2, person3);当然也可以这样Arrays.asList(person1, person2, person3);

在比较对象大小的时候都知道有两种方式:

1.实体类实现Conparable接口;2.在Collections.sort()实现Comparator接口

在guava中的对象比较,实现的Comparator可以这样写:

new Comparator<Person>() {

            @Override

            public int compare(Person o1, Person o2) {

                return ComparisonChain.start().compare(o1.getName(), o2.getName()).compare(o1.getAge(), o2.getAge())

                        .result();

            }

}

还有很多功能还要自己去摸索学习,此处省略.............


打赏
最近浏览
zero杨  LV2 2019年12月2日
安安an  LV17 2019年7月23日
aliger  LV11 2018年7月3日
203778513  LV9 2017年9月13日
lanmaokyle  LV2 2017年8月8日
金仁杰  LV2 2017年5月5日
winamy  LV1 2017年4月26日
zhouxinming  LV3 2017年4月17日
lvcai88  LV4 2017年4月13日
微微上翘  LV23 2017年3月22日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友