1. package guava;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.util.ArrayList;
  6. import java.util.Comparator;
  7. import java.util.Date;
  8. import java.util.HashMap;
  9. import java.util.HashSet;
  10. import java.util.List;
  11. import java.util.Map;
  12. import java.util.Set;
  13.  
  14. import com.google.common.base.CharMatcher;
  15. import com.google.common.base.Charsets;
  16. import com.google.common.base.Function;
  17. import com.google.common.base.Joiner;
  18. import com.google.common.base.Preconditions;
  19. import com.google.common.base.Splitter;
  20. import com.google.common.collect.ArrayListMultimap;
  21. import com.google.common.collect.ImmutableList;
  22. import com.google.common.collect.ImmutableMap;
  23. import com.google.common.collect.ImmutableSet;
  24. import com.google.common.collect.Lists;
  25. import com.google.common.collect.MapDifference;
  26. import com.google.common.collect.Maps;
  27. import com.google.common.collect.Multimap;
  28. import com.google.common.collect.Multimaps;
  29. import com.google.common.collect.Ordering;
  30. import com.google.common.collect.Sets;
  31. import com.google.common.collect.Sets.SetView;
  32. import com.google.common.io.Files;
  33. import com.google.common.primitives.Doubles;
  34. import com.google.common.primitives.Ints;
  35.  
  36. import static com.google.common.base.Predicates.*;
  37. import static com.google.common.collect.Iterables.*;
  38.  
  39. public class Test {
  40. private String title;
  41. private Date date;
  42. private String author;
  43.  
  44. public static void main(String[] args) {
  45. // 普通Collection的创建
  46. List<String> list = Lists.newArrayList();
  47. Set<String> set = Sets.newHashSet();
  48. Map<String, String> map = Maps.newHashMap();
  49.  
  50. // 不变Collection的创建
  51. ImmutableList<String> iList = ImmutableList.of("a", "b", "c");
  52. ImmutableSet<String> iSet = ImmutableSet.of("e1", "e2");
  53. ImmutableMap<String, String> iMap = ImmutableMap.of("k1", "v1", "k2", "v2");
  54.  
  55. // 文件读取演示
  56. File file = new File("/home/alexis/tests/text1");
  57. List<String> content = null;
  58. try {
  59. content = Files.readLines(file, Charsets.UTF_8);
  60. } catch (IOException ex) {
  61. ex.printStackTrace();
  62. }
  63. for (String line : content) {
  64. System.out.println(line);
  65. }
  66.  
  67. // 基本类型操作
  68. int[] arr = {1, 2, 3};
  69. int[] arr2 = {1, 2, 3};
  70. int intCmp = Ints.compare(1, 2);
  71. int doubleCmp = Doubles.compare(1.1, 1.2);
  72. int index = Ints.indexOf(arr, 1);
  73. boolean contains = Ints.contains(arr, 1);
  74. int max = Ints.max(arr);
  75. int min = Ints.min(arr);
  76. int[] arr3 = Ints.concat(arr, arr2);
  77.  
  78. // List转数组
  79. List<Integer> intList = Lists.newArrayList(1, 2, 3);
  80. int[] intArr = Ints.toArray(intList);
  81.  
  82. // 便利字符匹配类 CharMatcher
  83. // 判断匹配结果
  84. boolean result = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')).matches('K');
  85. // 保留数字文本
  86. String s1 = CharMatcher.DIGIT.retainFrom("abc 123 efg");
  87. // 删除数字文本
  88. String s2 = CharMatcher.DIGIT.removeFrom("abc 123 efg");
  89. // 更多方法参见 http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/CharMatcher.html
  90.  
  91. // Joiner 与 Splitter
  92. // 使用 "/" 串联字符串
  93. String[] subdirs = { "usr", "local", "lib" };
  94. String path = Joiner.on("/").join(subdirs);
  95. System.out.println(path);
  96.  
  97. // 使用 "," 切分字符串并去除空串与空格
  98. String s = "dog ,,, cat,fish,";
  99. Iterable<String> i = Splitter.on(',').omitEmptyStrings().trimResults().split(s);
  100. for (String ss : i) {
  101. System.out.println(ss);
  102. }
  103.  
  104. // 集合过滤器
  105. // 使用自定义回调方法对Map的每个Value进行操作
  106. ImmutableMap<String, Double> m = ImmutableMap.of("a", 1.1, "b", 1.2);
  107. // Function<F, T> F表示apply()方法input的类型,T表示apply()方法返回类型
  108. Map<String, Double> m2 = Maps.transformValues(m, new Function<Double, Double>() {
  109. double e = 1.2;
  110. @Override
  111. public Double apply(Double input) {
  112. return input * e;
  113. }
  114. });
  115. System.out.println(m2);
  116.  
  117. // 条件过滤集合
  118. // 方法来自 com.google.common.collect.Iterables 以及 com.google.common.base.Predicates
  119. ImmutableList<String> names = ImmutableList.of("Aleksander", "Jaran", "Integrasco", "Guava", "Java");
  120. Iterable<String> fitered = filter(names, or(equalTo("Aleksander"), equalTo("Jaran")));
  121. System.out.println(fitered);
  122.  
  123. // 对计划排序,并生成排序后的集合拷贝视图
  124. Man man1 = new Man("Alexis", "Drazen");
  125. Man man2 = new Man("Bob", "Lee");
  126. Man man3 = new Man("Vince", "Carter");
  127. ImmutableList<Man> men = ImmutableList.of(man1, man2, man3);
  128.  
  129. Comparator<Man> byLastName = new Comparator<Man>() {
  130. public int compare(final Man p1, final Man p2) {
  131. return p1.getLastName().compareTo(p2.getLastName());
  132. }
  133. };
  134.  
  135. Comparator<Man> byFirstName = new Comparator<Man>() {
  136. public int compare(final Man p1, final Man p2) {
  137. return p1.getFirstName().compareTo(p2.getFirstName());
  138. }
  139. };
  140.  
  141. // 先按 lastName 再按 firstName 排序,最后倒序
  142. List<Man> sortedCopy = Ordering.from(byLastName).compound(byFirstName).reverse().sortedCopy(men);
  143. System.out.println(sortedCopy);
  144.  
  145. // 集合的合集,交集,差集
  146. HashSet<Integer> setA = Sets.newHashSet(1, 2, 3, 4, 5);
  147. HashSet<Integer> setB = Sets.newHashSet(4, 5, 6, 7, 8);
  148.  
  149. SetView<Integer> union = Sets.union(setA, setB);
  150. System.out.println("union:");
  151. for (Integer integer : union)
  152. System.out.println(integer);
  153.  
  154. SetView<Integer> difference = Sets.difference(setA, setB);
  155. System.out.println("difference:");
  156. for (Integer integer : difference)
  157. System.out.println(integer);
  158.  
  159. SetView<Integer> intersection = Sets.intersection(setA, setB);
  160. System.out.println("intersection:");
  161. for (Integer integer : intersection)
  162. System.out.println(integer);
  163.  
  164. // Map 的更多操作
  165. Map<String, String> mapA = ImmutableMap.of("k1", "v1", "k2", "v2", "k3", "v3");
  166. Map<String, String> mapB = ImmutableMap.of("k2", "v2", "k3", "v3", "k4", "v4");
  167. MapDifference<String, String> differenceMap = Maps.difference(mapA, mapB);
  168. differenceMap.areEqual();
  169. Map entriesDiffering = differenceMap.entriesDiffering();
  170. Map entriesOnlyOnLeft = differenceMap.entriesOnlyOnLeft();
  171. Map entriesOnlyOnRight = differenceMap.entriesOnlyOnRight();
  172. Map entriesInCommon = differenceMap.entriesInCommon();
  173. System.out.println(entriesDiffering);
  174. System.out.println(entriesOnlyOnLeft);
  175. System.out.println(entriesOnlyOnRight);
  176. System.out.println(entriesInCommon);
  177.  
  178. // 使用Preconditions进行校验,校验不通过会抛出相应的异常
  179. Test t = new Test("Tite", new Date(), "Author");
  180.  
  181. }
  182.  
  183. // Multimap的使用,Multimap<T1, T2>,T1表示Map的键,T2表示Value集合的集合元素类型
  184. Map<String, List<Man>> map = new HashMap<String, List<Man>>();
  185.  
  186. public void addMan1(String author, Man Man) {
  187. List<Man> Mans = map.get(author);
  188. if (Mans == null) {
  189. Mans = new ArrayList<Man>();
  190. map.put(author, Mans);
  191. }
  192. Mans.add(Man);
  193. }
  194.  
  195. // 使用Multimap替代以上代码
  196. Multimap<String, Man> multimap = ArrayListMultimap.create();
  197.  
  198. public void addMan2(String name, Man man) {
  199. multimap.put(name, man);
  200. }
  201.  
  202. // Multimap的高级应用
  203. // listOfMaps代表一个List中包含多个这种 mapOf("type", "blog", "id", "292", "author", "john"); 类型的Map
  204. // 现在需要根据type将这些map放在不同的list中
  205. List listOfMaps = null; // 这里省略 listOfMaps 的初始化
  206. Multimap<String, Map<String, String>> partitionedMap = Multimaps.index(
  207. listOfMaps,
  208. new Function<Map<String, String>, String>() {
  209. public String apply(final Map<String, String> from) {
  210. return from.get("type");
  211. }
  212. });
  213.  
  214. // 使用Preconditions进行校验
  215. public Test(String title, Date date, String author) {
  216. this.title = Preconditions.checkNotNull(title);
  217. this.date = Preconditions.checkNotNull(date);
  218. this.author = Preconditions.checkNotNull(author);
  219. }
  220. }

Guava的使用的更多相关文章

  1. Spring cache简单使用guava cache

    Spring cache简单使用 前言 spring有一套和各种缓存的集成方式.类似于sl4j,你可以选择log框架实现,也一样可以实现缓存实现,比如ehcache,guava cache. [TOC ...

  2. Guava库介绍之实用工具类

    作者:Jack47 转载请保留作者和原文出处 欢迎关注我的微信公众账号程序员杰克,两边的文章会同步,也可以添加我的RSS订阅源. 本文是我写的Google开源的Java编程库Guava系列之一,主要介 ...

  3. Google Java编程库Guava介绍

    本系列想介绍下Java下开源的优秀编程库--Guava[ˈgwɑːvə].它包含了Google在Java项目中使用一些核心库,包含集合(Collections),缓存(Caching),并发编程库(C ...

  4. [Java 缓存] Java Cache之 Guava Cache的简单应用.

    前言 今天第一次使用MarkDown的形式发博客. 准备记录一下自己对Guava Cache的认识及项目中的实际使用经验. 一: 什么是Guava Guava工程包含了若干被Google的 Java项 ...

  5. [转载]Google Guava官方教程(中文版)

      原文链接  译文链接 译者: 沈义扬,罗立树,何一昕,武祖  校对:方腾飞 引言 Guava工程包含了若干被Google的 Java项目广泛依赖 的核心库,例如:集合 [collections] ...

  6. java开发人员,最应该学习和熟练使用的工具类。google guava.(谷歌 瓜娃)

    学习参考文章: http://blog.csdn.net/wisgood/article/details/13297535 http://ifeve.com/google-guava/ http:// ...

  7. Guava学习笔记(一)概览

    Guava是谷歌开源的一套Java开发类库,以简洁的编程风格著称,提供了很多实用的工具类, 在之前的工作中应用过Collections API和Guava提供的Cache,不过对Guava没有一个系统 ...

  8. Guava monitor

    Guava的com.google.util.concurrent类库提供了相对于jdk java.util.concurrent包更加方便实用的并发类,Monitor类就是其中一个.Monitor类在 ...

  9. 使用Guava EventBus构建publish/subscribe系统

    Google的Guava类库提供了EventBus,用于提供一套组件内publish/subscribe的解决方案.事件总线EventBus,用于管理事件的注册和分发.在系统中,Subscribers ...

  10. Guava Supplier实例

    今天想讲一下Guava Suppliers的几点用法.Guava Suppliers的主要功能是创建包裹的单例对象,通过get方法可以获取对象的值.每次获取的对象都为同一个对象,但你和单例模式有所区别 ...

随机推荐

  1. LoadRunner web_add_header()

    Action() { web_cleanup_cookies(); web_cache_cleanup(); web_url("entrypoint", "URL=htt ...

  2. 五 Python基础 数据类型和变量

    数据类型 计算机顾名思义就是可以做数学计算的机器,因此,计算机程序理所当然地可以处理各种数值.但是,计算机能处理的远不止数值,还可以处理文本.图形.音频.视频.网页等各种各样的数据,不同的数据,需要定 ...

  3. 基于Ubuntu系统搭建以太坊go-ethereum源码的开发环境

    第一.先安装geth的CLI环境sudo apt-get install geth,这个很重要 第二.下载源代码 git clone https://github.com/ethereum/go-et ...

  4. Python画一朵花

    from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import Line ...

  5. Java_关键字、匿名对象、内部类、访问修饰符、代码块

    final关键字 概述: 继承的出现提高了代码的复用性,并方便开发.但随之也有问题,有些类在描述完之后,不想被继承,或者有些类中的部分方法功能是固定的,不想让子类重写.可是当子类继承了这些特殊类之后, ...

  6. 洛谷——P2071 座位安排 seat.cpp/c/pas

    P2071 座位安排 seat.cpp/c/pas 题目背景 公元二零一四年四月十七日,小明参加了省赛,在一路上,他遇到了许多问题,请你帮他解决. 题目描述 已知车上有N排座位,有N*2个人参加省赛, ...

  7. post登录趴一趴百度贴吧美女

    本次爬取的贴吧是百度的美女吧,给广大男同胞们一些激励 在爬取之前需要在浏览器先登录百度贴吧的帐号,各位也可以在代码中使用post提交或者加入cookie 爬行地址:http://tieba.baidu ...

  8. FastReport.Net使用:[31]使用带参查询及存储

    带参查询 1.在数据列表中创建一个名为姓名的参数. 然后使用一个对话框,将文本框的ReportParameter(报表参数)选为参数中的姓名. 给童鞋们的一个题目:这里可以改为下拉框,学生列表从数据库 ...

  9. FastReport.Net使用:[10]报表栏目说明

    报表栏目说明 报表标题(Report Title):在每个报表的开始时打印. 报表合计区(Report Summary):在报表结尾时打印,显示在最后一行数据后,页脚前. 页眉(Page Header ...

  10. 【BZOJ 2510】 2510: 弱题 (矩阵乘法、循环矩阵的矩阵乘法)

    2510: 弱题 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 374  Solved: 196 Description 有M个球,一开始每个球均有一 ...