Guava的使用
- package guava;
- import java.io.File;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import com.google.common.base.CharMatcher;
- import com.google.common.base.Charsets;
- import com.google.common.base.Function;
- import com.google.common.base.Joiner;
- import com.google.common.base.Preconditions;
- import com.google.common.base.Splitter;
- import com.google.common.collect.ArrayListMultimap;
- import com.google.common.collect.ImmutableList;
- import com.google.common.collect.ImmutableMap;
- import com.google.common.collect.ImmutableSet;
- import com.google.common.collect.Lists;
- import com.google.common.collect.MapDifference;
- import com.google.common.collect.Maps;
- import com.google.common.collect.Multimap;
- import com.google.common.collect.Multimaps;
- import com.google.common.collect.Ordering;
- import com.google.common.collect.Sets;
- import com.google.common.collect.Sets.SetView;
- import com.google.common.io.Files;
- import com.google.common.primitives.Doubles;
- import com.google.common.primitives.Ints;
- import static com.google.common.base.Predicates.*;
- import static com.google.common.collect.Iterables.*;
- public class Test {
- private String title;
- private Date date;
- private String author;
- public static void main(String[] args) {
- // 普通Collection的创建
- List<String> list = Lists.newArrayList();
- Set<String> set = Sets.newHashSet();
- Map<String, String> map = Maps.newHashMap();
- // 不变Collection的创建
- ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
- ImmutableSet<String> iSet = ImmutableSet.of("e1", "e2");
- ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");
- // 文件读取演示
- File file = new File("/home/alexis/tests/text1");
- List<String> content = null;
- try {
- content = Files.readLines(file, Charsets.UTF_8);
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- for (String line : content) {
- System.out.println(line);
- }
- // 基本类型操作
- int[] arr = {1, 2, 3};
- int[] arr2 = {1, 2, 3};
- int intCmp = Ints.compare(1, 2);
- int doubleCmp = Doubles.compare(1.1, 1.2);
- int index = Ints.indexOf(arr, 1);
- boolean contains = Ints.contains(arr, 1);
- int max = Ints.max(arr);
- int min = Ints.min(arr);
- int[] arr3 = Ints.concat(arr, arr2);
- // List转数组
- List<Integer> intList = Lists.newArrayList(1, 2, 3);
- int[] intArr = Ints.toArray(intList);
- // 便利字符匹配类 CharMatcher
- // 判断匹配结果
- boolean result = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).matches('K');
- // 保留数字文本
- String s1 = CharMatcher.DIGIT.retainFrom("abc 123 efg");
- // 删除数字文本
- String s2 = CharMatcher.DIGIT.removeFrom("abc 123 efg");
- // 更多方法参见 http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/CharMatcher.html
- // Joiner 与 Splitter
- // 使用 "/" 串联字符串
- String[] subdirs = { "usr", "local", "lib" };
- String path = Joiner.on("/").join(subdirs);
- System.out.println(path);
- // 使用 "," 切分字符串并去除空串与空格
- String s = "dog ,,, cat,fish,";
- Iterable<String> i = Splitter.on(',').omitEmptyStrings().trimResults().split(s);
- for (String ss : i) {
- System.out.println(ss);
- }
- // 集合过滤器
- // 使用自定义回调方法对Map的每个Value进行操作
- ImmutableMap<String, Double> m = ImmutableMap.of("a", 1.1, "b", 1.2);
- // Function<F, T> F表示apply()方法input的类型,T表示apply()方法返回类型
- Map<String, Double> m2 = Maps.transformValues(m, new Function<Double, Double>() {
- double e = 1.2;
- @Override
- public Double apply(Double input) {
- return input * e;
- }
- });
- System.out.println(m2);
- // 条件过滤集合
- // 方法来自 com.google.common.collect.Iterables 以及 com.google.common.base.Predicates
- ImmutableList<String> names = ImmutableList.of("Aleksander", "Jaran", "Integrasco", "Guava", "Java");
- Iterable<String> fitered = filter(names, or(equalTo("Aleksander"), equalTo("Jaran")));
- System.out.println(fitered);
- // 对计划排序,并生成排序后的集合拷贝视图
- Man man1 = new Man("Alexis", "Drazen");
- Man man2 = new Man("Bob", "Lee");
- Man man3 = new Man("Vince", "Carter");
- ImmutableList<Man> men = ImmutableList.of(man1, man2, man3);
- Comparator<Man> byLastName = new Comparator<Man>() {
- public int compare(final Man p1, final Man p2) {
- return p1.getLastName().compareTo(p2.getLastName());
- }
- };
- Comparator<Man> byFirstName = new Comparator<Man>() {
- public int compare(final Man p1, final Man p2) {
- return p1.getFirstName().compareTo(p2.getFirstName());
- }
- };
- // 先按 lastName 再按 firstName 排序,最后倒序
- List<Man> sortedCopy = Ordering.from(byLastName).compound(byFirstName).reverse().sortedCopy(men);
- System.out.println(sortedCopy);
- // 集合的合集,交集,差集
- HashSet<Integer> setA = Sets.newHashSet(1, 2, 3, 4, 5);
- HashSet<Integer> setB = Sets.newHashSet(4, 5, 6, 7, 8);
- SetView<Integer> union = Sets.union(setA, setB);
- System.out.println("union:");
- for (Integer integer : union)
- System.out.println(integer);
- SetView<Integer> difference = Sets.difference(setA, setB);
- System.out.println("difference:");
- for (Integer integer : difference)
- System.out.println(integer);
- SetView<Integer> intersection = Sets.intersection(setA, setB);
- System.out.println("intersection:");
- for (Integer integer : intersection)
- System.out.println(integer);
- // Map 的更多操作
- Map<String, String> mapA = ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3");
- Map<String, String> mapB = ImmutableMap.of("k2", "v2", "k3", "v3", "k4", "v4");
- MapDifference<String, String> differenceMap = Maps.difference(mapA, mapB);
- differenceMap.areEqual();
- Map entriesDiffering = differenceMap.entriesDiffering();
- Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();
- Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();
- Map entriesInCommon = differenceMap.entriesInCommon();
- System.out.println(entriesDiffering);
- System.out.println(entriesOnlyOnLeft);
- System.out.println(entriesOnlyOnRight);
- System.out.println(entriesInCommon);
- // 使用Preconditions进行校验,校验不通过会抛出相应的异常
- Test t = new Test("Tite", new Date(), "Author");
- }
- // Multimap的使用,Multimap<T1, T2>,T1表示Map的键,T2表示Value集合的集合元素类型
- Map<String, List<Man>> map = new HashMap<String, List<Man>>();
- public void addMan1(String author, Man Man) {
- List<Man> Mans = map.get(author);
- if (Mans == null) {
- Mans = new ArrayList<Man>();
- map.put(author, Mans);
- }
- Mans.add(Man);
- }
- // 使用Multimap替代以上代码
- Multimap<String, Man> multimap = ArrayListMultimap.create();
- public void addMan2(String name, Man man) {
- multimap.put(name, man);
- }
- // Multimap的高级应用
- // listOfMaps代表一个List中包含多个这种 mapOf("type", "blog", "id", "292", "author", "john"); 类型的Map
- // 现在需要根据type将这些map放在不同的list中
- List listOfMaps = null; // 这里省略 listOfMaps 的初始化
- 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");
- }
- });
- // 使用Preconditions进行校验
- public Test(String title, Date date, String author) {
- this.title = Preconditions.checkNotNull(title);
- this.date = Preconditions.checkNotNull(date);
- this.author = Preconditions.checkNotNull(author);
- }
- }
Guava的使用的更多相关文章
- Spring cache简单使用guava cache
Spring cache简单使用 前言 spring有一套和各种缓存的集成方式.类似于sl4j,你可以选择log框架实现,也一样可以实现缓存实现,比如ehcache,guava cache. [TOC ...
- Guava库介绍之实用工具类
作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...
- Google Java编程库Guava介绍
本系列想介绍下Java下开源的优秀编程库--Guava[ˈgwɑːvə].它包含了Google在Java项目中使用一些核心库,包含集合(Collections),缓存(Caching),并发编程库(C ...
- [Java 缓存] Java Cache之 Guava Cache的简单应用.
前言 今天第一次使用MarkDown的形式发博客. 准备记录一下自己对Guava Cache的认识及项目中的实际使用经验. 一: 什么是Guava Guava工程包含了若干被Google的 Java项 ...
- [转载]Google Guava官方教程(中文版)
原文链接 译文链接 译者: 沈义扬,罗立树,何一昕,武祖 校对:方腾飞 引言 Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] ...
- java开发人员,最应该学习和熟练使用的工具类。google guava.(谷歌 瓜娃)
学习参考文章: http://blog.csdn.net/wisgood/article/details/13297535 http://ifeve.com/google-guava/ http:// ...
- Guava学习笔记(一)概览
Guava是谷歌开源的一套Java开发类库,以简洁的编程风格著称,提供了很多实用的工具类, 在之前的工作中应用过Collections API和Guava提供的Cache,不过对Guava没有一个系统 ...
- Guava monitor
Guava的com.google.util.concurrent类库提供了相对于jdk java.util.concurrent包更加方便实用的并发类,Monitor类就是其中一个.Monitor类在 ...
- 使用Guava EventBus构建publish/subscribe系统
Google的Guava类库提供了EventBus,用于提供一套组件内publish/subscribe的解决方案.事件总线EventBus,用于管理事件的注册和分发.在系统中,Subscribers ...
- Guava Supplier实例
今天想讲一下Guava Suppliers的几点用法.Guava Suppliers的主要功能是创建包裹的单例对象,通过get方法可以获取对象的值.每次获取的对象都为同一个对象,但你和单例模式有所区别 ...
随机推荐
- LoadRunner web_add_header()
Action() { web_cleanup_cookies(); web_cache_cleanup(); web_url("entrypoint", "URL=htt ...
- 五 Python基础 数据类型和变量
数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种各样的数据,不同的数据,需要定 ...
- 基于Ubuntu系统搭建以太坊go-ethereum源码的开发环境
第一.先安装geth的CLI环境sudo apt-get install geth,这个很重要 第二.下载源代码 git clone https://github.com/ethereum/go-et ...
- Python画一朵花
from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import Line ...
- Java_关键字、匿名对象、内部类、访问修饰符、代码块
final关键字 概述: 继承的出现提高了代码的复用性,并方便开发.但随之也有问题,有些类在描述完之后,不想被继承,或者有些类中的部分方法功能是固定的,不想让子类重写.可是当子类继承了这些特殊类之后, ...
- 洛谷——P2071 座位安排 seat.cpp/c/pas
P2071 座位安排 seat.cpp/c/pas 题目背景 公元二零一四年四月十七日,小明参加了省赛,在一路上,他遇到了许多问题,请你帮他解决. 题目描述 已知车上有N排座位,有N*2个人参加省赛, ...
- post登录趴一趴百度贴吧美女
本次爬取的贴吧是百度的美女吧,给广大男同胞们一些激励 在爬取之前需要在浏览器先登录百度贴吧的帐号,各位也可以在代码中使用post提交或者加入cookie 爬行地址:http://tieba.baidu ...
- FastReport.Net使用:[31]使用带参查询及存储
带参查询 1.在数据列表中创建一个名为姓名的参数. 然后使用一个对话框,将文本框的ReportParameter(报表参数)选为参数中的姓名. 给童鞋们的一个题目:这里可以改为下拉框,学生列表从数据库 ...
- FastReport.Net使用:[10]报表栏目说明
报表栏目说明 报表标题(Report Title):在每个报表的开始时打印. 报表合计区(Report Summary):在报表结尾时打印,显示在最后一行数据后,页脚前. 页眉(Page Header ...
- 【BZOJ 2510】 2510: 弱题 (矩阵乘法、循环矩阵的矩阵乘法)
2510: 弱题 Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 374 Solved: 196 Description 有M个球,一开始每个球均有一 ...