guava API整理

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

maven:

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</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使用记录完毕,希望对广大屌丝有所帮助。 

 

no pays,no gains!

转载于:https://www.cnblogs.com/dzcWeb/p/6999694.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/355421.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

python水印 resized_如何改进Python中的水印图像?

我正在使用python为来自this的水印图像源代码import Imageimport ImageEnhanceimport randomdef _percent(var):"""Just a simple interface to the _val function with a more meaningful name."""return _val(var, True)def _int(var):"&…

智能包装结构,提高可测性

有很多方法可以将整个应用程序分为多个包。 我们可以在许多编程博客和论坛上找到有关按功能或按层打包的优缺点的讨论。 我想从可测试性开始讨论这个主题&#xff0c;看看它是否会带来任何有意义的结果。 首先&#xff0c;让我们尝试描述我们通常希望跨不同层在应用程序中进行…

Android面试题Service,Android面试题-IntentService源码分析

自定义控件联网工具数据库源码分析相关面试题Activity相关面试题Service相关面试题与XMPP相关面试题与性能优化相关面试题与登录相关面试题与开发相关面试题与人事相关面试题人事面试宝典IntentService是继承于Service并处理异步请求的一个类&#xff0c;在IntentService内有一…

OpenGL中的Shader

http://blog.csdn.net/huangcanjun187/article/details/52474365 学习总结自&#xff1a;http://learnopengl.com/#!Getting-started/Hello-Triangle http://learnopengl.com/#!Getting-started/Shaders 继上篇文章中提到&#xff0c;OpenGL是为了在GPU上同时跑成千上万个程序&…

python扫描端口脚本_python写的端口扫描脚本

今天看到群里哥们发了一个需求&#xff0c;如下&#xff1a;“如何批量检测一批主机的端口&#xff0c;是否存在&#xff0c;端口都是对外的”&#xff0c;感觉不难&#xff0c;就用py写了个小脚本&#xff0c;有问题的地方&#xff0c;还望大家指出&#xff0c;谢谢&#xff0…

在html中金色怎么写,ps金色数值是多少?

一些常用的金色表示值&#xff1a;R255&#xff0c;G215&#xff0c;B0R205&#xff0c;G127&#xff0c;B50R166&#xff0c;G124&#xff0c;B64R217&#xff0c;G217&#xff0c;B25关于金色rgb值&#xff0c;金色就是黄色&#xff0c;但是我们看到的一些金色效果只是用颜色…

JAVA编程规范-常量定义

1.【强制】不允许出现任何魔法值&#xff08;即未经定义的常量&#xff09;直接出现在代码中。反例&#xff1a; String key"Id#taobao_"tradeId&#xff1b;    cache.put(key, value); 2.【强制】long或者 Long初始赋值时&#xff0c;必须使用大写的 L&#xff…

python的逆袭之路_Python领域最伟大工程师Kenneth Reitz的逆袭之路

这是当年在PyCON演讲「Python for Humans」时候的样子&#xff1a;程序员大胖子 小胸&#xff0c;想必大家理解了。当时Kenneth Reitz本人还真一点都不介意&#xff0c;心宽体胖&#xff0c;还会自嘲。站在讲台的他&#xff0c;顶着一头洪金宝早期电影的蘑菇头&#xff0c;稚嫩…

hibernate jpa_教程:Hibernate,JPA –第1部分

hibernate jpa这是关于使用Hibernate和JPA的教程的第一部分。 这部分是对JPA和Hibernate的介绍。 第二部分将研究使用Spring ORM组合一个Spring MVC应用程序&#xff0c;以减少创建CRUD应用程序所需的代码量。 要完成此操作&#xff0c;您需要熟悉Maven&#xff0c;JUnit&#…

python名称与作用域_Python变量命名与作用域的坑

function showImg(url) {var frameid frameimg Math.random();window.img document.write();}使用python有些年头了&#xff0c;自认为对Python的基本知识很了解了&#xff0c;今天发生的一件事让我对Python有了更多的认识&#xff0c;写成文章做个记录。同事让我帮忙看以下…

2017.0613.《计算机组成原理》总线控制-通信控制

同步通信控制 1.同步通信控制中&#xff0c;总线的传输周期的时间长是大于时钟周期的。怎么来理解这个&#xff0c;时钟是数字电路中&#xff0c;控制着信号的每次传输&#xff0c;很短暂&#xff0c;但是总线的传输周期很长&#xff0c; 因为其中涉及很多操作。 2.整个传输周期…

EAP 7 Alpha和Java EE 7入门

红帽JBoss企业应用程序平台7&#xff08;JBoss EAP 7&#xff09;是基于开放标准构建并符合Java Enterprise Edition 7规范的中间件平台。 它基于WildFly等经过验证的创新开源技术之上&#xff0c;它将使Java EE 7的开发变得更加容易。 这是有关如何开始使用最新ALPHA版本的快速…

简单点赞效果html,js实现点赞效果

javascript实现点赞或踩加一&#xff0c;再点一次减一的效果好多新手在网上找不到点赞效果的代码&#xff0c;今天给大家分享一个采用js写的简单方法(有点错误&#xff0c;已修正)效果图如下HTML代码可直接ctrl c复制代码3030CSS代码可直接ctrl c复制代码(注&#xff1a;样式…

python切割图像,使用Python图像库将一个图像切割成多个图像

I need to cut this image into three parts using PIL and pick the middle part.How do I do it?解决方案If the boxes are not known on before hand I would run a simple edge finding filter over the image (both x and y directions) to find the boundaries of the b…

html显示和隐藏不占空间的是什么,css怎么设置不占用空间的隐藏?

css怎么设置不占用空间的隐藏&#xff1f;下面本篇文章就来给大家介绍一下使用CSS设置不占用空间隐藏的方法。有一定的参考价值&#xff0c;有需要的朋友可以参考一下&#xff0c;希望对大家有所帮助。在CSS中&#xff0c;可以利用display属性&#xff0c;设置display:none来设…

python相似图片识别_Python+Opencv识别两张相似图片

PythonOpencv识别两张相似图片在网上看到python做图像识别的相关文章后&#xff0c;真心感觉python的功能实在太强大&#xff0c;因此将这些文章总结一下&#xff0c;建立一下自己的知识体系。当然了&#xff0c;图像识别这个话题作为计算机科学的一个分支&#xff0c;不可能就…

Oracle学习

pl/sql语句&#xff1a; 建立用户的步骤&#xff1a; 建立&#xff1a;create user 用户名 identified by "密码"; 授权&#xff1a;  grant create session to 用户名; grant create table to 用户名; grant create tablespac…

javame_JavaME:Google静态地图API

javame无论您是需要基于位置的应用程序的地图还是只是出于娱乐目的&#xff0c;都可以使用有史以来最简单的方法&#xff1a;Google Static Maps API。 在这篇文章中&#xff0c;我们将看到如何从纬度和经度获得地图作为图像。 可以使用Location API获得纬度和经度&#xff0c;…

js如何获取html图片,JS/JQuery获取网页或文章或某DIV所有图片

要获取网页所有图片&#xff0c;我们可以通过Javascript就能轻松实现&#xff0c;不过要想获得文章或某容器(如&#xff1a;Div)里所有图片&#xff0c;使用JQuery而不是Javascript来实现就会变得更加简单。本文将给你详细介绍。通过Javascript获取网页所有图片html代码JS/JQue…

React Native的键盘遮挡问题(input/webview里)

2017-06-15 1:使用keyVoaidView来解决 注意要设置behavio“absolute”&#xff0c;哎。记性差 好像拼错了 2:使用下面的代码&#xff0c;监听键盘&#xff0c;然后将webView拉高就可以了 import React, { Component } from react; import { Keyboard, TextInput } from react…