Guava用法总结

说明:这篇文章是参考了网络上的多篇文章而做的汇总。


1.校验Preconditions

通常我们检查参数,是用如下方法:

        public void setRating(Double rating){

                if(rating == null){

                        throw new NullPointerException();

                }

                Double r = rating;

        }

使用Guava,可以这样:

        public void setRating(Double rating){

                Double r = checkNotNull(rating);

        }

对于下面这样的:

if (count <= 0) 

throw new IllegalArgumentException("must be positive: " + count); 

}

只需这样:

checkArgument(count > 0, "must be positive: %s", count);

2.Stopwatch(计时器)

我们经常需要判断某一段语句执行需要多少时间,过去常用的做法是记录运行前的时间,然后用运行完成的时间减去运行前的时间,并且转换成我们可读的秒或是毫秒时间,在guava中的做法是:

//Stopwatch stopwatch = new Stopwatch().start();

Stopwatch stopwatch = Stopwatch.createStarted();

//do something test

for (int i = 0; i < 10000; i++) 

{

}

long nanos = stopwatch.elapsed(TimeUnit.NANOSECONDS);

System.out.println(nanos);

3.String Joining 字符串连接

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

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

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

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

可以这么使用Joiner: 

String[] subdirs = { "usr", "local", "lib" };

String directory = Joiner.on("/").join(subdirs);

或者这样: 

int[] numbers = { 1, 2, 3, 4, 5 };

String numbersAsString = Joiner.on(";").join(Ints.asList(numbers));

还可以更加简化:

String numbersAsStringDirectly = Ints.join(";", numbers);

4.String Splitting字符串分割

有这样一组字符串“hello,,qiyadeng,com,”我们用split(,)分割字符串,得到的结果是["hello","","qiyaeng","com"],但是我们如果希望的是把空值去掉,还需要另外处理,使用guavaSplitter可以简单做到。

Iterable<String> splitStr = Splitter.on(',').trimResults().omitEmptyStrings().split("hello,qiyadeng,com");

更加高级的:

String str = "key1: 1; key2: 2  ; key3: 3";

Map<String,String> m = Splitter.on(';').trimResults().withKeyValueSeparator(":").split(str);

Output:->

{key1= 1, key2= 2, key3= 3}

5.字符串处理CharMatcher

如果你想从字符串中得到所有的数字,那么你可以这样: 

String string = CharMatcher.DIGIT.retainFrom("some text 89983 and more");

如果你想把字符串中的数字都去掉,可以如下: 

String string = CharMatcher.DIGIT.removeFrom("some text 89983 and more");

6.基本类型的便捷工具类

假如有一个整型数字数组,我们想知道数组中是否有特定的整型数字。传统的写法如下: 

 

int[] array = { 1, 2, 3, 4, 5 };

int a = 4;

boolean hasA = false;

for (int i : array) {

if (i == a) {

hasA = true;

}

}

使用Guava,我们可以如下: 

boolean contains = Ints.contains(array, a);

同样,其他类型的基本型数组也可以这么来做。我们甚至可以直接对数组做如下的事: 

int indexOf = Ints.indexOf(array, a);

int max = Ints.max(array);

int min = Ints.min(array);

int[] concat = Ints.concat(array, array2);

7.简化的集合用法

以前这么写:

Map<String, Map<Long, List<String>>> map = new HashMap<String, Map<Long,List<String>>>();

现在可以这样写:

Map<String, Map<Long, List<String>>> map = Maps.newHashMap();

或者更甚者直接使用静态导入: 

Map<String, Map<Long, List<String>>>map = newHashMap();

同样地:

Lists.newArrayList();

Sets.newHashSet();

构造数据以前是这样的:

List<String> list = new ArrayList<String>();

list.add("a");

list.add("b");

list.add("c");

list.add("d");

现在可以这样:

ImmutableList<String> of = ImmutableList.of("a", "b", "c", "d");

ImmutableMap<String,String> map = ImmutableMap.of("key1", "value1", "key2", "value2");

8.便捷的文件读取

从文件中按行读取内容: 

File file = new File(getClass().getResource("/test.txt").getFile());

List<String> lines = null;

try {

lines = Files.readLines(file, Charsets.UTF_8);

} catch (IOException e) {

e.printStackTrace();

}

9.强大的Function对象转换

举个例子,假设你有一个Mapkey是物品,value是对应的价格,单位是欧元。那么,你有个需求是将里面的价格都转换为美元,传统的做法是遍历整个Map,然后更新每个value值,将价格转换为美元价格。现在通过Function只需要这样:

Map usdPriceMap = Maps.transformValues(eurPriceMap, new Function() {

    double eurToUsd = 1.4888;

    public Double apply(final Double from) {

        return from * eurToUsd;

    }

});

10.Ordering实现复杂的排序

对集合进行排序我们可以使用JDK提供的Collections类: Collections.sort(List<T>, Comparator<? super T>)

但有时候我们想做更复杂一些的事情,比如合并多个Comparator或者我们可能只是想要排序过的集合的一个视图,而不改变原来集合的顺序。Guava给我们提供了Ordering,让我们更好地掌控排序。假如我们有两个对Person类排序的comparator,一个是根据lastName排序,一个是根据firstName排序:

Comparator<Person> byLastName = new Comparator<Person>() {

    public int compare(final Person p1, final Person p2) {

        return p1.getLastName().compareTo(p2.getLastName());

    }

}

 

Comparator<Person> byFirstName = new Comparator<Person>() {

    public int compare(final Person p1, final Person p2) {

        return p1.getFirstName().compareTo(p2.getFirstName());

    }

};

那么,假如我们现在想先根据last name排序,再根据first name排序,然后对排序结果反序,那就可以这样: 

List<Person> sortedCopy = Ordering.from(byLastName).compound(byFirstName).reverse().sortedCopy(persons);

11.Predicate过滤集合

假设有一个姓名列表想要过滤:

List<String> names = Lists.newArrayList("Aleksander", "Jaran", "Integrasco", "Guava", "Java");

如果我们想要过滤后的列表中只包含Aleksander或者Jaran或者名字长度小于5的成员,就可以这样:

private static class LengthLessThanPredicate implements Predicate<String> {

    private final int length;

    private LengthLessThanPredicate(final int length) {

        this.length = length;

    }

    public boolean apply(final String s) {

        return s.length() < length;

    }

}

public static Predicate<String> lengthLessThan(final int length) {

    return new LengthLessThanPredicate(length);

}

Iterable<String> filtered = filter(names, or(or(equalTo("Aleksander"),equalTo("Jaran")), lengthLessThan(5)));

12.集合的交集、并集和差集

HashSet setA = newHashSet(1, 2, 3, 4, 5);

HashSet setB = newHashSet(4, 5, 6, 7, 8);

 

SetView union = Sets.union(setA, setB);

System.out.println("union:");

for (Integer integer : union)

    System.out.println(integer);        

 

SetView difference = Sets.difference(setA, setB);

System.out.println("difference:");

for (Integer integer : difference)

    System.out.println(integer);       

 

SetView intersection = Sets.intersection(setA, setB);

System.out.println("intersection:");

for (Integer integer : intersection)

System.out.println(integer);

对于Map,可以像下面这样处理

MapDifference differenceMap = Maps.difference(mapA, mapB);

如果用MapDifference类,我们还可以这样:

differenceMap.areEqual();

Map entriesDiffering = differenceMap.entriesDiffering();

Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();

Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();

Map entriesInCommon = differenceMap.entriesInCommon();

13.一键多值Map---Multimap

以前这样实现:

Map<Person, List<BlogPost>> map = new HashMap<Person, List<BlogPost>>();

 

public void addBlogPost(final Person author, final BlogPost blogPost) {

    List<BlogPost> blogPosts = map.get(author);

    if (blogPosts == null) {

        blogPosts = new ArrayList<BlogPost>();

        map.put(author, blogPosts);

    }

    blogPosts.add(blogPost);

}

现在可以这样:

Multimap<Person, BlogPost> multimap = ArrayListMultimap.create();

 

public void addBlogPost(final Person author, final BlogPost blogPost) {

    multimap.put(author, blogPost)

}

14.集合重组

List<Map<String, String>> listOfMaps =  Lists.newArrayList();

ImmutableMap<String,String> map = null;

for (int i = 0; i < 3; i++)

{

map = ImmutableMap.of("type""blog""id""10"+(i+1), "author""john"+(i+1));

listOfMaps.add(map);

}

for (int i = 0; i < 5; i++)

{

map = ImmutableMap.of("type""news""id""20"+(i+1), "author""hugh"+(i+1));

listOfMaps.add(map);

}

Multimap<String, Map<String, String>> partitionedMap = Multimaps.index(listOfMaps, new Function<Map<String, String>, String>() {

    public String apply(final Map<String, String> from) {

        return from.get("type");

    }

});

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值