import com.google.common.base.*; import com.google.common.base.Optional; import com.google.common.collect.*; import java.text.SimpleDateFormat; import java.util.*; public class GuavaTester { public String ss = "123"; public static void main (String args[]) { // nullOptional(); //GuavaTester t =new GuavaTester(); // t.objects(); // range(); //preconditions(); //ordering(); //throwables(); //multiset(); //bimap(); //table(); //=========== //list(); //filter(); //transform(); //compose(); // testGuava6(); //testGuava7(); //multiset(); //multimap(); //biMap(); //=========== //LoadingCache //Joiner //Splitter //CharMatcher //CaseFormat } /** * HashMap 键唯一,值可以重复 * BiMap:双向Map(bidirectional Map) 键与值不能重复(unique -valued map) */ public static void biMap () { BiMap<String, String> biMap = HashBiMap.create(); biMap.put("sina", "@sina.com"); biMap.put("qq", "@qq.com"); //通过邮箱找用户 String user = biMap.inverse().get("@sina.com"); System.out.println(user); System.out.println(biMap.inverse().inverse() == biMap); } public static void multimap () { Map<String, String> map = new HashMap<String, String>(); //加入测试数据 map.put("改革开放", "邓爷爷"); map.put("三个代表", "江主席"); map.put("科学发展观", "胡主席"); map.put("和谐社会", "胡主席"); map.put("八荣八耻", "胡主席"); //Multimap Multimap<String, String> teacher = ArrayListMultimap.create(); //迭代器 Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); String key = entry.getKey(); //课程 String value = entry.getValue(); //教师 //教师--->课程 teacher.put(value, key); } //查看Multimap Set<String> keySet = teacher.keySet(); for (String key : keySet) { Collection<String> col = teacher.get(key); System.out.println(key + ":" + col); } } /** * 统计单词出现的次数 * 1、HashMap 分拣存储+面向对象思维 --->判断 * 2、Multiset:无序可重复 .count() 增强可读性+操作简单 */ public static void testGuava7 () { String str = "this is a cat and that is mice where is the food"; //分割字符串 String[] arr = str.split(" "); //存储到Multiset中 Multiset<String> set = HashMultiset.create(); for (String ss : arr) { set.add(ss); } //获取所有的单词set Set<String> letters = set.elementSet(); for (String temp : letters) { System.out.println(temp + ":" + set.count(temp)); } } public static void multiset () { Multiset<Integer> multiset = HashMultiset.create(); multiset.add(new Integer(1)); multiset.add(new Integer(1)); multiset.stream().forEach(x -> System.out.print(x + " ")); System.out.println(); Set<Integer> integers = multiset.elementSet(); System.out.println("=" + integers.size() + "="); } public static void transform () { Set<Long> timeSet = Sets.newHashSet(); //类型转换 timeSet.add(19990701L); timeSet.add(20080808L); timeSet.add(20161212L); Collection<String> timeStrCol = Collections2.transform(timeSet, new Function<Long, String>() { @Override public String apply (Long input) { return new SimpleDateFormat("yyyy-MM-dd").format(input); } }); for (String temp : timeStrCol) { System.out.println(temp); } } public static void filter () { //创建List 静态初始化 List<String> list = Lists.newArrayList("moon", "son", "dad", "refer"); //找出回文 palindronme backwoeds mirror words Collection<String> palindromeList = Collections2.filter(list, new Predicate<String>() { @Override public boolean apply (String input) { //业务逻辑 return new StringBuilder(input).reverse().toString().equals(input); } }); for (String temp : palindromeList) { System.out.println(temp); //输出结果:dad refer } } public static void list () { List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); //对原有的list进行包装,相当于原有List的一个试图,快照,不够安全 List<String> readList = Collections.unmodifiableList(list); //java.lang.UnsupportedOperationException //readList.add("d"); list.add("d"); //改变原有List 试图也一起改变 //对比查看初始化List guava对只读设置 安全可靠,并且相对简单 List<String> immutableList = ImmutableList.of("a", "b", "c"); immutableList.add("d");//java.lang.UnsupportedOperationException } public static void table () { Table<String, String, String> employeeTable = HashBasedTable.create(); employeeTable.put("IBM", "101", "Mahesh"); Map<String, String> ibmEmployees = employeeTable.row("IBM"); } public static void bimap () { BiMap<Integer, String> empIDNameMap = HashBiMap.create(); empIDNameMap.put(new Integer(101), "Mahesh"); empIDNameMap.put(new Integer(102), "Sohan"); empIDNameMap.put(new Integer(103), "Ramesh"); System.out.println(empIDNameMap.inverse().get("Mahesh")); empIDNameMap.putIfAbsent(104, "hansc"); empIDNameMap.computeIfAbsent(104, k -> k + "x"); empIDNameMap.forEach((k, v) -> System.out.println("key = " + k + ",value=" + v)); } public static void throwables () { // Throwables.propagateIfPossible(); } public static void ordering () { List<Integer> numbers = new ArrayList<Integer>(); numbers.add(new Integer(5)); numbers.add(new Integer(2)); numbers.add(new Integer(15)); numbers.add(new Integer(51)); Ordering ordering = Ordering.natural(); System.out.println("Input List: "); System.out.println(numbers); Collections.sort(numbers, ordering); System.out.println("Sorted List: "); System.out.println(numbers); System.out.println("======================"); System.out.println("List is sorted: " + ordering.isOrdered(numbers)); System.out.println("Minimum: " + ordering.min(numbers)); System.out.println("Maximum: " + ordering.max(numbers)); Collections.sort(numbers, ordering.reverse()); System.out.println("Reverse: " + numbers); numbers.add(null); numbers.add(1); numbers.add(1000); System.out.println("Null added to Sorted List: "); System.out.println(numbers); Collections.sort(numbers, ordering.nullsFirst().reverse()); System.out.println("Null first Sorted List: "); System.out.println(numbers); System.out.println("======================"); } public static void preconditions () { Preconditions.checkArgument(0 < 1, "sorry ,you are wrong"); String s = ""; Preconditions.checkNotNull(s, "%s ... %s", "哈哈", "呵呵"); } public static void range () { Range<Integer> range = Range.closed(1, 3); if (range.contains(2)) { System.out.print("true"); } Range<Short> all = Range.all(); System.out.println(all.atLeast(100)); DiscreteDomain discreteDomain = DiscreteDomain.integers(); long distance = discreteDomain.distance(3, 6); System.out.println(distance); ContiguousSet<Integer> contiguousSet = ContiguousSet.create(range, discreteDomain); for (Integer i : contiguousSet) { System.out.println(i + " "); } } private static void nullOptional () { Integer value = 1; // of 非空 检查, 否则抛出异常 Optional<Integer> a = Optional.of(value); Optional<Integer> b = Optional.of(new Integer(1)); // asSet 返回单值得集合 System.out.println("asSet 返回单值得集合 = " + a.asSet()); // Optional equals 方法 System.out.println("Optional equals 方法" + a.equals(b)); System.out.println(sum(a, b)); Integer nullEle = 1; Optional<Integer> c = Optional.of(nullEle); nullEle = c.or(123); System.out.println("absent = " + c.absent().isPresent()); //System.out.println("fromNullable = " + c.fromNullable()); System.out.println(c.orNull()); c = Optional.fromNullable(null); c.get(); } public static Integer sum (Optional<Integer> a, Optional<Integer> b) { return a.get() + b.get(); } /** * 集合操作:交集、差集、并集 */ public void testGuava6 () { Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4); Set<Integer> set2 = Sets.newHashSet(3, 4, 5, 6); //交集 Sets.SetView<Integer> inter = Sets.intersection(set1, set2); //差集 Sets.SetView<Integer> diff = Sets.difference(set1, set2); //并集 Sets.SetView<Integer> union = Sets.union(set1, set2); //遍历输出:交集 :3,4 差集:1,2,5,6 并集:1,2,3,4,5,6, } /** * 组合式函数编程 */ public void compose () { List<String> list = Lists.newArrayList("abcde", "good", "happiness"); //确保容器中的字符串长度不超过5 Function<String, String> f1 = new Function<String, String>() { @Override public String apply (String input) { return input.length() > 5 ? input.substring(0, 5) : input; } }; //转成大写 Function<String, String> f2 = new Function<String, String>() { @Override public String apply (String input) { return input.toUpperCase(); } }; //String = f2(f1(String)) Function<String, String> f = Functions.compose(f1, f2); Collection<String> resultCol = Collections2.transform(list, f); for (String str : resultCol) { System.out.println(str); /* * 输出结果: ABCDE GOOD HAPPI */ } } public void objects () { String s = "first"; String s2 = "test"; String res = MoreObjects.firstNonNull(s, s2); System.out.println(res); MoreObjects.ToStringHelper toStringHelper = MoreObjects.toStringHelper(this); toStringHelper.add("hansc", "123"); System.out.print(toStringHelper.toString()); // java 8 StringJoiner 替代 MoreObjects.toStringHelper String string = new StringJoiner(", ", this.getClass().getSimpleName() + "[", "]") .add("userId=" + 1) .add("timestamp=" + 2) .toString(); System.out.print(string); } }