您的位置:首页 > 编程语言 > Java开发

Guava简介及初体验

2015-10-31 19:31 615 查看
Guava是google提供的一个Java第三方库,旨在提供更简洁、优雅的api,让代码更加易读,易写、易用。

先看它的结构图:



而其中经常用到的如注解(annotations)、缓存(cache)、集合(collect)、哈希(hash)、io、数学运算(math)、net、原生类型(primitives)、反射(reflect)、并发(concurrent)。

下面将按照我的学习顺序依次介绍Guava.

Collect

Guava为我们提供了许多Java之外的集合以及集合工具类,主要分为四大类:不可变集合、新集合类型、集合工具类、扩展工具类。

不可变集合

ImmutableList<Integer> immutableList = ImmutableList.of(1, 2, 3, 4);
ImmutableBiMap<Integer, String> immutableBiMap = ImmutableBiMap.of(1, "1", 2, "2");
ImmutableSet<Integer> immutableSet = ImmutableSet.of(1, 2, 3, 4);
ImmutableCollection<Integer> immutableCollection = ImmutableList.of(1, 2, 3, 4);

for (Integer i : immutableList) {
System.out.print(i + "-");
}
System.out.println();
for (Integer i : immutableBiMap.keySet()) {
System.out.print(immutableBiMap.get(i) + "-");
}
System.out.println();
for (Integer i : immutableList) {
System.out.print(i + "-");
}
System.out.println();
for (Integer i : immutableCollection) {
System.out.print(i + "-");
}


运行结果:

1-2-3-4-

1-2-

1-2-3-4-

1-2-3-4-

新集合类型

[Google Guava] 2.2-新集合类型

集合工具类



这里用Lists举例

ArrayList<Integer> list = Lists.newArrayList(new Integer[]{1,2,3,4});

List<String> transform = Lists.transform(list, new Function<Integer, String>() {
@Override
public String apply(Integer integer) {
return integer + "";
}
});

List<Integer> reverseList = Lists.reverse(list);
for (Object o : transform) {
System.out.println(o.getClass().toString() + o);
}
for (Object o : reverseList) {
System.out.println(o);
}


运行结果:

class java.lang.String1

class java.lang.String2

class java.lang.String3

class java.lang.String4

4

3

2

1

扩展工具类

让实现和扩展集合类变得更容易,想要了解更多信息,可以转到[Google Guava] 2.4-集合扩展工具类
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java Guava