google guava使用介绍

guava简介

  Google Guava很优秀,大有取代Apache Commons之势。Guava是用来,用原汁原味的英文来说就是“Our goal is for you to write less code and for the code you do write to be simpler, cleaner, and more readable”,Guava中主要包括Basic Utilities,Collections,Caches,Functional Idioms,Concurrency,Strings,Primitives Support,Ranges,I/O等等。下面介绍一些它的简单使用例子:
1、预先判断Preconditions
  可以用在方法的开始或者是构造函数的开始,对于不合法的校验可以快速报错。

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;

public class PreconditionsDemo {
    public static void main(String[] args) {
        new Car(null);//Exception in thread "main" java.lang.NullPointerException
        //Exception in thread "main" java.lang.IllegalArgumentException: speed (0.0) must be positive
        new Car("Audi").drive(0);
    }
}

class Car {
    private String name;

    public Car(String name) {
        this.name = checkNotNull(name);//NPE Null Pointer Exception
    }

    public void drive(double speed) {
        checkArgument(speed > 0.0, "speed (%s) must be positive", speed);
    }
}

除了checkNotNull之外,Preconditions还提供了一些其他的方法,如chekArgument, checkState, checkElementIndex, checkPositionIndex等,更多可参考Preconditions API。

2、Object.toStringHelper()
  这个方法主要是用于更加简单的实现Object.toString()方法。

import com.google.common.base.MoreObjects;

public class MoreObjectsDemo {
    private String name;
    private String userId;
    private String petName;
    private String sex;

    @Override
    public String toString() {
        //prints:MoreObjectsDemo{name=testName, userId=NO1, petName=PIG}
        return MoreObjects.toStringHelper(this).add("name", "testName").add("userId", "NO1").add("petName", "PIG").omitNullValues().toString();
        //prints:MoreObjectsDemo{name=testName, userId=NO1, petName=PIG}
        //return MoreObjects.toStringHelper(this).add("name", "testName").add("userId", "NO1").add("petName", "PIG").toString();
    }
    public static void main(String[] args) {
        System.out.println(new MoreObjectsDemo());
    }
}

3、Stopwatch(计时器)
  我们经常需要判断某一段语句执行需要多少时间,过去常用的做法是记录运行前的时间,然后用运行完成的时间减去运行前的时间,并且转换成我们可读的秒或是毫秒时间(这个转换过程可并不简单),在guava中可以有一个更好的方法:

import com.google.common.base.Stopwatch;

public class StopWatchDemo {
    public static void main(String[] args) {

        final Stopwatch stopwatch = Stopwatch.createUnstarted().start();
        //start
        stopwatch.start();
        try {
            System.out.println("You can do something!");
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        stopwatch.stop();
        long nanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);
        System.out.println(nanos);//1000076976
    }
}

附:TimeUUnit可选值有:
  NANOSECONDS 毫微秒 十亿分之一秒(就是微秒/1000)
  MICROSECONDS 微秒 一百万分之一秒(就是毫秒/1000)
  MILLISECONDS 毫秒 千分之一秒
  SECONDS 秒
  MINUTES 分钟
  HOURS 小时
  DAYS 天

4、CharMatcher
  字符匹配的方法特别多,举一个例子过滤用户的输出。

import com.google.common.base.CharMatcher;

public class CharMatcherDemo {
    private static final CharMatcher ID_MATCHER = CharMatcher.DIGIT.or(CharMatcher.is('-'));

    public static void main(String[] args) {
        String userID = "123454-333";
        String s = ID_MATCHER.retainFrom(userID);
        System.out.println(s);//123454-333
        s = ID_MATCHER.retainFrom("1    test    11-222");
        System.out.println(s);//可以把输入的的字符类型去掉,111-222
    }
}

5、String Joining 字符串连接
  可以快速地把一组字符数组连接成为用特殊符合连接的一个字符串,如果这组字符中有null值的话,我们可以使用skipNulls或是useForNull来控制我们要输出的内容。

//Joiner JOINER= Joiner.on(",").skipNulls();

Joiner JOINER= Joiner.on(",").useForNull("null");

String str = JOINER.join("hello","world",null,"qiyadeng");

//hello,world,null,qiyadeng

6、String Splitting字符串分割
  有这样一组字符串”hello, ,qiyadeng,com,”我们用split(“,”)分割字符串,得到的结果是[“hello”,”“,”qiyaeng”,”com”],但是我们如果希望的是把空值去掉,还需要另外处理,使用guava的Splitter可以简单做到。使用指定的分隔符对字符串进行拆分,默认对空白符不做任何处理,并且不会静默的丢弃末尾分隔符,如果需要处理的话要显式调用trimResults(),omitEmptyStrings()。

 public class SplitterDemo {
    public static void main(String[] args) {
        Iterable<String> split = Splitter.on(',').trimResults().omitEmptyStrings().split("foo, ,bar,quux,blue,");
        for (String s : split) {
            System.out.print(s + "---");//foo---bar---quux---blue---
        }
        System.out.println();
        String[] split1 = "foo, ,bar,quux,blue,".split(",");
        for (String s : split1) {
            System.out.print(s + "---");//foo--- ---bar---quux---blue---
        }
    }
}

7、Guava的官方API参考文档:
http://google.github.io/guava/releases/snapshot/api/docs/
https://github.com/google/guava

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值