1,大纲

让我们来熟悉瓜娃,并体验下它的一些API,分成如下几个部分:

  • Introduction
  • Guava Collection API
  • Guava Basic Utilities
  • IO API
  • Cache API

2,为神马选择瓜娃?

  • 瓜娃是java API蛋糕上的冰激凌(精华)
  • 高效设计良好的API.
  • 被google的开发者设计,实现和使用。
  • 遵循高效的java这本书的好的语法实践。
  • 使代码更刻度,简洁,简单。
  • 使用java 1.5的特性,
  • 流行的API,动态的开发
  • 它提供了大量相关的应用类,集合,多线程,比较,字符串,输入输出,缓存,网络,原生类型,数学,反射等等
  • 百分百的单元测试,被很多的项目使用,帮助开发者专注业务逻辑而不是写java应用类
  • 节省时间,资源,提高生产力
  • 我的目的是为基本的java特征提供开源代码的支持,而不是自己再写一个
  • Apache Common库-Apache是一个很好的成熟的库,但是不支持泛型,Apache对早起的java版本很有用,(1.5之前的)
  • java7,java8 最新的java支持一些guava的API

guava最新的正式版本是14.0-rc2,这个版本需要java1.6支持.

最新的maven坐标是:

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>14.0-rc2</version>
</dependency>

3,集合API的使用

  3.1简化工作

可以简化集合的创建和初始化;

类别 原来的写法 guava的写法
集合创建

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

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

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

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

//1,简化集合的创建
List<Person> personList= Lists.newLinkedList();
Set<Person> personSet= Sets.newHashSet();
Map<String,Person> personMap= Maps.newHashMap();
Integer[] intArrays= ObjectArrays.newArray(Integer.class,10);

集合初始化

Set<String> set = new HashSet<String>();

set.add("one");

set.add("two");

set.add("three");

Set<String> set = Sets.newHashSet("one","two","three");

List<String> list = Lists.newArrayList("one","two","three");

Map<String, String> map = ImmutableMap.of("ON","TRUE","OFF","FALSE");

//2,简化集合的初始化
List<Person> personList2= Lists.newArrayList(new Person(1, 1, "a", "46546", 1, 20),

new Person(2, 1, "a", "46546", 1, 20));
Set<Person> personSet2= Sets.newHashSet(new Person(1,1,"a","46546",1,20),

new Person(2,1,"a","46546",1,20));
Map<String,Person> personMap2= ImmutableMap.of("hello",new Person(1,1,"a","46546",1,20),"fuck",new Person(2,1,"a","46546",1,20));

3.2 不变性

很大一部分是google集合提供了不变性,不变对比可变:

  • 数据不可改变
  • 线程安全
  • 不需要同步逻辑
  • 可以被自由的共享
  • 容易设计和实现
  • 内存和时间高效

不变对比不可修改

google的不变被确保真正不可改变,而不可修改实际上还是可以修改数据;如下所示:

Set<Integer> data = new HashSet<Integer>();

data.addAll(Arrays.asList(10, 20, 30, 40, 50, 60, 70, 80));

Set<Integer> fixedData = Collections.unmodifiableSet(data); // fixedData - [50, 70, 80, 20, 40, 10, 60, 30]

data.add(90); // fixedData - [50, 70, 80, 20, 40, 10, 90, 60, 30]

如何创建不可变的集合:

ImmutableSet<Integer> numbers = ImmutableSet.of(10, 20, 30, 40, 50);

使用copyOf方法

ImmutableSet<Integer> another = mmutableSet.copyOf(numbers);

使用Builder方法

ImmutableSet<Integer> numbers2 = ImmutableSet.<Integer>builder().addAll(numbers) .add(60) .add(70).add(80).build();

//3,创建不可变的集合

ImmutableList<Person> personImmutableList=
ImmutableList.of(new Person(1, 1, "a", "46546", 1, 20), new Person(2, 1, "a", "46546", 1, 20));

ImmutableSet<Person> personImmutableSet=ImmutableSet.copyOf(personSet2);

ImmutableMap<String,Person> personImmutableMap=ImmutableMap.<String,Person>builder()
.put("hell",new Person(1,1,"a","46546",1,20)).putAll(personMap2) .build();

3.3 新的集合类型

The Guava API provides very useful new collection types that work very nicely with existing java collections.

guava API 提供了有用的新的集合类型,协同已经存在的java集合工作的很好。

分别是 MultiMap, MultiSet, Table, BiMap, ClassToInstanceMap

种类 写的例子
MultiMap

一种key可以重复的map,子类有ListMultimap和SetMultimap,对应的通过key分别得到list和set

Multimap<String, Person> customersByType =ArrayListMultimap.create();customersByType.put("abc", new Person(1, 1, "a", "46546", 1, 20));

customersByType.put("abc", new Person(1, 1, "a", "46546", 1, 30));
customersByType.put("abc", new Person(1, 1, "a", "46546", 1, 40));
customersByType.put("abc", new Person(1, 1, "a", "46546", 1, 50));
customersByType.put("abcd", new Person(1, 1, "a", "46546", 1, 50));
customersByType.put("abcde", new Person(1, 1, "a", "46546", 1, 50));

for(Person person:customersByType.get("abc"))
{
System.out.println(person.getAge());
}

MultiSet

不是集合,可以增加重复的元素,并且可以统计出重复元素的个数,例子如下:

private static void testMulitiSet() {
Multiset<Integer> multiSet = HashMultiset.create();
multiSet.add(10);
multiSet.add(30);
multiSet.add(30);
multiSet.add(40);

System.out.println( multiSet.count(30)); // 2
System.out.println( multiSet.size()); //4
}

Table

相当于有两个key的map,不多解释

private static void testTable() {
Table<Integer,Integer,Person> personTable=HashBasedTable.create();
personTable.put(1,20,new Person(1, 1, "a", "46546", 1, 20));
personTable.put(0,30,new Person(2, 1, "ab", "46546", 0, 30));
personTable.put(0,25,new Person(3, 1, "abc", "46546", 0, 25));
personTable.put(1,50,new Person(4, 1, "aef", "46546", 1, 50));
personTable.put(0,27,new Person(5, 1, "ade", "46546",0, 27));
personTable.put(1,29,new Person(6, 1, "acc", "46546", 1, 29));
personTable.put(0,33,new Person(7, 1, "add", "46546",0, 33));
personTable.put(1,66,new Person(8, 1, "afadsf", "46546", 1, 66));

//1,得到行集合
Map<Integer,Person> rowMap= personTable.row(0);
int maxAge= Collections.max(rowMap.keySet());

}

BiMap 是一个一一映射,可以通过key得到value,也可以通过value得到key;

private static void testBitMap() {
//双向map
BiMap<Integer,String> biMap=HashBiMap.create();

biMap.put(1,"hello");
biMap.put(2,"helloa");
biMap.put(3,"world");
biMap.put(4,"worldb");
biMap.put(5,"my");
biMap.put(6,"myc");

int value= biMap.inverse().get("my");
System.out.println("my --"+value);

}

ClassToInstanceMap

有的时候,你的map的key并不是一种类型,他们是很多类型,你想通过映射他们得到这种类型,guava提供了ClassToInstanceMap满足了这个目的。
 
除了继承自Map接口,ClassToInstaceMap提供了方法 T getInstance(Class<T>) 和 T putInstance(Class<T>, T),消除了强制类型转换。
 
该类有一个简单类型的参数,通常称为B,代表了map控制的上层绑定,例如:
 
ClassToInstanceMap<Number> numberDefaults = MutableClassToInstanceMap.create();
numberDefaults.putInstance(Integer.class, Integer.valueOf(0));
从技术上来说,ClassToInstanceMap<B> 实现了Map<Class<? extends B>, B>,或者说,这是一个从B的子类到B对象的映射,这可能使得ClassToInstanceMap的泛型轻度混乱,但是只要记住B总是Map的上层绑定类型,通常来说B只是一个对象。
guava提供了有用的实现, MutableClassToInstanceMap 和 ImmutableClassToInstanceMap.
重点:像其他的Map<Class,Object>,ClassToInstanceMap 含有的原生类型的项目,一个原生类型和他的相应的包装类可以映射到不同的值;

private static void testClass() {
ClassToInstanceMap<Person> classToInstanceMap =MutableClassToInstanceMap.create();

Person person= new Person(1,20,"abc","46464",1,100);

classToInstanceMap.putInstance(Person.class,person);

// System.out.println("string:"+classToInstanceMap.getInstance(String.class));
// System.out.println("integer:" + classToInstanceMap.getInstance(Integer.class));

Person person1=classToInstanceMap.getInstance(Person.class);

}

3.4 谓词和筛选

谓词(Predicate)是用来筛选集合的;

谓词是一个简单的接口,只有一个方法返回布尔值,但是他是一个很令人惊讶的集合方法,当你结合collections2.filter方法使用,这个筛选方法返回原来的集合中满足这个谓词接口的元素;

举个例子来说:筛选出集合中的女人

public static void main(String[] args)
{
Optional<ImmutableMultiset<Person>> optional=Optional.fromNullable(testPredict());

if(optional.isPresent())
{
for(Person p:optional.get())
{
System.out.println("女人:"+p);
}
}

System.out.println(optional.isPresent());
}

public static ImmutableMultiset<Person> testPredict()
{
List<Person> personList=Lists.newArrayList(new Person(1, 1, "a", "46546", 1, 20),
new Person(2, 1, "ab", "46546", 0, 30),
new Person(3, 1, "abc", "46546", 0, 25),
new Person(4, 1, "aef", "46546", 1, 50),
new Person(5, 1, "ade", "46546",0, 27),
new Person(6, 1, "acc", "46546", 1, 29),
new Person(7, 1, "add", "46546",0, 33));

return ImmutableMultiset.copyOf(Collections2.filter(personList,new Predicate<Person>() {
@Override
public boolean apply( Person input) {
return input.getSex()==0;
}
}));
}

Predicates含有一些内置的筛选方法,比如说 in ,and ,not等,根据实际情况选择使用。

3.5 功能和转换

转换一个集合为另外一个集合;

实例如下:

public static void main(String[] args)
{
Optional<ImmutableMultiset<String>> optional=Optional.fromNullable(testTransform());

if(optional.isPresent())
{
for(String p:optional.get())
{
System.out.println("名字:"+p);
}
}

System.out.println(optional.isPresent());
}

public static ImmutableMultiset<String> testTransform()
{
List<Person> personList=Lists.newArrayList(new Person(1, 1, "a", "46546", 1, 20),
new Person(2, 1, "ab", "46546", 0, 30),
new Person(3, 1, "abc", "46546", 0, 25),
new Person(4, 1, "aef", "46546", 1, 50),
new Person(5, 1, "ade", "46546",0, 27),
new Person(6, 1, "acc", "46546", 1, 29),
new Person(7, 1, "add", "46546",0, 33));

return ImmutableMultiset.copyOf(Lists.transform(personList,new Function<Person, String>() {
@Override
public String apply( Person input) {
return input.getName();
}
}));
}

3.6 排序

是guava一份非常灵活的比较类,可以被用来操作,扩展,当作比较器,排序提供了集合排序的很多控制;

实例如下:

Lists.newArrayList(30, 20, 60, 80, 10);

Ordering.natural().sortedCopy(numbers); //10,20,30,60,80

Ordering.natural().reverse().sortedCopy(numbers); //80,60,30,20,10

Ordering.natural().min(numbers); //10

Ordering.natural().max(numbers); //80

Lists.newArrayList(30, 20, 60, 80, null, 10);

Ordering.natural().nullsLast().sortedCopy(numbers); //10, 20,30,60,80,null

Ordering.natural().nullsFirst().sortedCopy(numbers); //null,10,20,30,60,80

public static void testOrdering()
{
List<Person> personList=Lists.newArrayList(
new Person(3, 1, "abc", "46546", 0, 25),
new Person(2, 1, "ab", "46546", 0, 30),
new Person(5, 1, "ade", "46546",0, 27),
new Person(1, 1, "a", "46546", 1, 20),
new Person(6, 1, "acc", "46546", 1, 29),
new Person(4, 1, "aef", "46546", 1, 50),
new Person(7, 1, "add", "46546",0, 33)
);

Ordering<Person> byAge=new Ordering<Person>() {
@Override
public int compare( Person left, Person right) {
return right.getAge()-left.getAge();
}
};

for(Person p: byAge.immutableSortedCopy(personList))
{
System.out.println(p);
}
}

学习笔记(二) 瓜娃(guava)的API快速熟悉使用的更多相关文章

  1. angular学习笔记(二十三)-$http(1)-api

    之前说到的$http.get和$http.post,都是基于$http的快捷方式.下面来说说完整的$http: $http(config) $http接受一个json格式的参数config: conf ...

  2. java8新特性学习笔记(二) 使用流(各种API)

    筛选和切片 用谓词筛选,筛选出各个不相同的元素,忽略流中的头几个元素,或将流截断至指定长度 用谓词筛选 Stream接口支持filter方法,该操作接受一个谓词(返回一个boolean的函数) 作为参 ...

  3. guava 学习笔记(二) 瓜娃(guava)的API快速熟悉使用

    guava 学习笔记(二) 瓜娃(guava)的API快速熟悉使用 1,大纲 让我们来熟悉瓜娃,并体验下它的一些API,分成如下几个部分: Introduction Guava Collection ...

  4. guava 学习笔记 使用瓜娃(guava)的选择和预判断使代码变得简洁

    guava 学习笔记 使用瓜娃(guava)的选择和预判断使代码变得简洁 1,本文翻译自 http://eclipsesource.com/blogs/2012/06/06/cleaner-code- ...

  5. ZooKeeper学习笔记二:API基本使用

    Grey ZooKeeper学习笔记二:API基本使用 准备工作 搭建一个zk集群,参考ZooKeeper学习笔记一:集群搭建. 确保项目可以访问集群的每个节点 新建一个基于jdk1.8的maven项 ...

  6. NumPy学习笔记 二

    NumPy学习笔记 二 <NumPy学习笔记>系列将记录学习NumPy过程中的动手笔记,前期的参考书是<Python数据分析基础教程 NumPy学习指南>第二版.<数学分 ...

  7. python3.4学习笔记(二十三) Python调用淘宝IP库获取IP归属地返回省市运营商实例代码

    python3.4学习笔记(二十三) Python调用淘宝IP库获取IP归属地返回省市运营商实例代码 淘宝IP地址库 http://ip.taobao.com/目前提供的服务包括:1. 根据用户提供的 ...

  8. amazeui学习笔记二(进阶开发5)--Web 组件开发规范Rules

    amazeui学习笔记二(进阶开发5)--Web 组件开发规范Rules 一.总结 1.见名知意:见那些class名字知意,见函数名知意,见文件名知意 例如(HISTORY.md Web 组件更新历史 ...

  9. AJax 学习笔记二(onreadystatechange的作用)

    AJax 学习笔记二(onreadystatechange的作用) 当发送一个请求后,客户端无法确定什么时候会完成这个请求,所以需要用事件机制来捕获请求的状态XMLHttpRequest对象提供了on ...

  10. java之jvm学习笔记二(类装载器的体系结构)

    java的class只在需要的时候才内转载入内存,并由java虚拟机的执行引擎来执行,而执行引擎从总的来说主要的执行方式分为四种, 第一种,一次性解释代码,也就是当字节码转载到内存后,每次需要都会重新 ...

随机推荐

  1. 题解 P5015 【标题统计】

    既然这个题这么水 大家不如来盘点一下算法呗 首先说一个事:逗号表达式 这玩意的值是最后一个表达式的值 那么我们就可以愉快的放进循环条件里摩擦 话说这个应该是基础吧,大多数代码都可以这样干 具体可以后面 ...

  2. python基础----析构函数__del__

    析构方法,当对象在内存中被释放时,自动触发执行. 注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行,所以,析构 ...

  3. Python多线程、进程、协程

    本节内容 操作系统发展史介绍 进程.与线程区别 python GIL全局解释器锁 线程 语法 join 线程锁之Lock\Rlock\信号量 将线程变为守护进程 Event事件 queue队列 生产者 ...

  4. Python中scatter()函数--转载

    原博地址:http://blog.csdn.net/anneqiqi/article/details/64125186 最近开始学习Python编程,遇到scatter函数,感觉里面的参数不知道什么意 ...

  5. 《提升c++性能的编程技术》读书笔记

    http://note.youdao.com/noteshare?id=9ab0eda264c85b774021426867e18eae

  6. hihocoder #1584 : Bounce

    题意; 有一个n*m的网格阵,球从左上角开始在网格中碰撞,碰到边界就直角反弹,到达格子的角落结束,求途中经过一次的格子数. 代码: //神马规律啊,设x表示球与垂直面的撞击次数,y为球与水平墙面的撞击 ...

  7. 题解 P3153 【[CQOI2009]跳舞】

    P3153 [CQOI2009]跳舞 题目描述 一次舞会有n个男孩和n个女孩.每首曲子开始时,所有男孩和女孩恰好配成n对跳交谊舞.每个男孩都不会和同一个女孩跳两首(或更多)舞曲.有一些男孩女孩相互喜欢 ...

  8. Installing kubectl

    Installing kubectl Kubernetes uses a command-line utility called kubectl for communicating with the ...

  9. C++ string类析构报错

    我项目中用到了字符串的Base64转码.DES解密等功能,可能DES解密算法只能解密8字节倍数长度的字符串,所以我得到的结果总会存在一个多余的“尾巴”,于是我想要做一个字符串尾部清理的工作.我的做法是 ...

  10. HTML5-Y音频与视频

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...