【无标题】

谷歌力作Guava

第一章 Guava环境设置
第二章 Guava Optional类
第三章 Guava Preconditions类
第四章 Guava Ordering类
第五章 Guava Objects类
第六章 Guava Range类
第七章 Guava Throwables类
第八章 Guava集合工具
第九章 Guava缓存工具
第十章 Guava字符串工具
第十一章 Guava数学工具



前言

Guava是一种基于开源的Java库,其中包含谷歌正在由他们很多项目使用的很多核心库。这个库是为了方便编码,并减少编码错误。这个库提供用于集合,缓存,支持原语,并发性,常见注解,字符串处理,I/O和验证的实用方法。


第一章 Guava环境设置

1.下载Guava存档

在这里插入图片描述
我下载的-18版本,但是现在已经是-23版本,大家自选即可。
分享地址Guava下载链接

2.设置Guava环境

在这里插入图片描述
在这里插入图片描述

第二章 Guava Optional类

Optional用于包含非空对象的不可变对象。 Optional对象,用于不存在值表示null。这个类有各种实用的方法,以方便代码来处理为可用或不可用,而不是检查null值。

类声明

@GwtCompatible(serializable=true)
public abstract class Optional<T> extends Object implements Serializable

类方法

在这里插入图片描述

Optional案例

import com.google.common.base.Optional;

public class GuavaTester {
   public static void main(String args[]){
      GuavaTester guavaTester = new GuavaTester();

      Integer value1 =  null;
      Integer value2 =  new Integer(10);
      //Optional.fromNullable - allows passed parameter to be null.
      Optional<Integer> a = Optional.fromNullable(value1);
      //Optional.of - throws NullPointerException if passed parameter is null
      Optional<Integer> b = Optional.of(value2);		

      System.out.println(guavaTester.sum(a,b));
   }

   public Integer sum(Optional<Integer> a, Optional<Integer> b){
      //Optional.isPresent - checks the value is present or not
      System.out.println("First parameter is present: " + a.isPresent());

      System.out.println("Second parameter is present: " + b.isPresent());

      //Optional.or - returns the value if present otherwise returns
      //the default value passed.
      Integer value1 = a.or(new Integer(0));	

      //Optional.get - gets the value, value should be present
      Integer value2 = b.get();

      return value1 + value2;
   }	
}

第三章 Guava Preconditions类

Preconditions提供静态方法来检查方法或构造函数,被调用是否给定适当的参数。它检查的先决条件。其方法失败抛出IllegalArgumentException。

类声明

@GwtCompatible
public final class Preconditions extends Object

类方法

在这里插入图片描述

Preconditions案例

import com.google.common.base.Preconditions;

public class GuavaTester {

   public static void main(String args[]){
      GuavaTester guavaTester = new GuavaTester();
      try {
         System.out.println(guavaTester.sqrt(-3.0));
      }catch(IllegalArgumentException e){
         System.out.println(e.getMessage());
      }
      try {
         System.out.println(guavaTester.sum(null,3));
      }catch(NullPointerException e){
         System.out.println(e.getMessage());
      }
      try {
         System.out.println(guavaTester.getValue(6));
      }catch(IndexOutOfBoundsException e){
         System.out.println(e.getMessage());
      }
   }

   public double sqrt(double input) throws IllegalArgumentException {
      Preconditions.checkArgument(input > 0.0,
         "Illegal Argument passed: Negative value %s.", input);
      return Math.sqrt(input);
   }	

   public int sum(Integer a, Integer b){
      a = Preconditions.checkNotNull(a,
         "Illegal Argument passed: First parameter is Null.");
      b = Preconditions.checkNotNull(b,
         "Illegal Argument passed: Second parameter is Null.");
      return a+b;
   }

   public int getValue(int input){
      int[] data = {1,2,3,4,5};
      Preconditions.checkElementIndex(input,data.length,
         "Illegal Argument passed: Invalid index.");
      return 0;
   }
}

第四章 Guava Ordering类

Ordering(排序)可以被看作是一个丰富的比较具有增强功能的链接,多个实用方法,多类型排序功能等。

类声明

@GwtCompatible
public abstract class Ordering<T> extends Object implements Comparator<T>

类方法

在这里插入图片描述

Ordering 案例

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.Ordering;

public class GuavaTester {
   public static void main(String args[]){
      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));
      numbers.add(new Integer(53));
      numbers.add(new Integer(35));
      numbers.add(new Integer(45));
      numbers.add(new Integer(32));
      numbers.add(new Integer(43));
      numbers.add(new Integer(16));

      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);
      System.out.println("Null added to Sorted List: ");
      System.out.println(numbers);		

      Collections.sort(numbers,ordering.nullsFirst());
      System.out.println("Null first Sorted List: ");
      System.out.println(numbers);
      System.out.println("======================");

      List<String> names = new ArrayList<String>();
      names.add("Ram");
      names.add("Shyam");
      names.add("Mohan");
      names.add("Sohan");
      names.add("Ramesh");
      names.add("Suresh");
      names.add("Naresh");
      names.add("Mahesh");
      names.add(null);
      names.add("Vikas");
      names.add("Deepak");

      System.out.println("Another List: ");
      System.out.println(names);

	  Collections.sort(names,ordering.nullsFirst().reverse());
      System.out.println("Null first then reverse sorted list: ");
      System.out.println(names);
   }
}

第五章 Guava Objects类

Objects类提供适用于所有对象,如equals, hashCode等辅助函数

类声明

@GwtCompatible
public final class Objects extends Object

类方法

在这里插入图片描述

示例

import com.google.common.base.Objects;

public class GuavaTester {
   public static void main(String args[]){
      Student s1 = new Student("Mahesh", "Parashar", 1, "VI");	
      Student s2 = new Student("Suresh", null, 3, null);	
	  
      System.out.println(s1.equals(s2));
      System.out.println(s1.hashCode());	
      System.out.println(
      Objects.toStringHelper(s1)
         .add("Name",s1.getFirstName()+" " + s1.getLastName())
         .add("Class", s1.getClassName())
         .add("Roll No", s1.getRollNo())
         .toString());
   }
}

class Student {
   private String firstName;
   private String lastName;
   private int rollNo;
   private String className;

   public Student(String firstName, String lastName, int rollNo, String className){
      this.firstName = firstName;
      this.lastName = lastName;
      this.rollNo = rollNo;
      this.className = className;		
   }

   @Override
   public boolean equals(Object object){
      if(!(object instanceof Student) || object == null){
         return false;
      }
      Student student = (Student)object;
      // no need to handle null here		
      // Objects.equal("test", "test") == true
      // Objects.equal("test", null) == false
      // Objects.equal(null, "test") == false
      // Objects.equal(null, null) == true		
      return Objects.equal(firstName, student.firstName) // first name can be null
         && Objects.equal(lastName, student.lastName) // last name can be null
         && Objects.equal(rollNo, student.rollNo)	
         && Objects.equal(className, student.className);// class name can be null
   }

   @Override
   public int hashCode(){
      //no need to compute hashCode by self
      return Objects.hashCode(className,rollNo);
   }
   public String getFirstName() {
      return firstName;
   }
   public void setFirstName(String firstName) {
      this.firstName = firstName;
   }
   public String getLastName() {
      return lastName;
   }
   public void setLastName(String lastName) {
      this.lastName = lastName;
   }
   public int getRollNo() {
      return rollNo;
   }
   public void setRollNo(int rollNo) {
      this.rollNo = rollNo;
   }
   public String getClassName() {
      return className;
   }
   public void setClassName(String className) {
      this.className = className;
   }
}

第六章 Guava Range类

Range 表示一个间隔或一个序列。它被用于获取一组数字/串在一个特定范围之内。

类声明

@GwtCompatible
public final class Range<C extends Comparable> extends Object implements Predicate<C>, Serializable

类方法

在这里插入图片描述

案例

import com.google.common.collect.ContiguousSet;
import com.google.common.collect.DiscreteDomain;
import com.google.common.collect.Range;
import com.google.common.primitives.Ints;

public class GuavaTester {

   public static void main(String args[]){
      GuavaTester tester = new GuavaTester();
      tester.testRange();
   }

   private void testRange(){

      //create a range [a,b] = { x | a <= x <= b}
      Range<Integer> range1 = Range.closed(0, 9);	
      System.out.print("[0,9] : ");
      printRange(range1);		
      System.out.println("5 is present: " + range1.contains(5));
      System.out.println("(1,2,3) is present: " + range1.containsAll(Ints.asList(1, 2, 3)));
      System.out.println("Lower Bound: " + range1.lowerEndpoint());
      System.out.println("Upper Bound: " + range1.upperEndpoint());

      //create a range (a,b) = { x | a < x < b}
      Range<Integer> range2 = Range.open(0, 9);
      System.out.print("(0,9) : ");
      printRange(range2);

      //create a range (a,b] = { x | a < x <= b}
      Range<Integer> range3 = Range.openClosed(0, 9);
      System.out.print("(0,9] : ");
      printRange(range3);

      //create a range [a,b) = { x | a <= x < b}
      Range<Integer> range4 = Range.closedOpen(0, 9);
      System.out.print("[0,9) : ");
      printRange(range4);

      //create an open ended range (9, infinity
      Range<Integer> range5 = Range.greaterThan(9);
      System.out.println("(9,infinity) : ");
      System.out.println("Lower Bound: " + range5.lowerEndpoint());
      System.out.println("Upper Bound present: " + range5.hasUpperBound());

      Range<Integer> range6 = Range.closed(3, 5);	
      printRange(range6);

      //check a subrange [3,5] in [0,9]
      System.out.println("[0,9] encloses [3,5]:" + range1.encloses(range6));

      Range<Integer> range7 = Range.closed(9, 20);	
      printRange(range7);
      //check ranges to be connected		
      System.out.println("[0,9] is connected [9,20]:" + range1.isConnected(range7));

      Range<Integer> range8 = Range.closed(5, 15);	

      //intersection
      printRange(range1.intersection(range8));

      //span
      printRange(range1.span(range8));
   }

   private void printRange(Range<Integer> range){		
      System.out.print("[ ");
      for(int grade : ContiguousSet.create(range, DiscreteDomain.integers())) {
         System.out.print(grade +" ");
      }
      System.out.println("]");
   }
}

第七章 Guava Throwables类

Throwable类提供了相关的Throwable接口的实用方法。

类声明

public final class Throwables extends Object

类方法

在这里插入图片描述

案例

import java.io.IOException;

import com.google.common.base.Objects;
import com.google.common.base.Throwables;

public class GuavaTester {
   public static void main(String args[]){
      GuavaTester tester = new GuavaTester();
      try {
         tester.showcaseThrowables();
      } catch (InvalidInputException e) {
         //get the root cause
         System.out.println(Throwables.getRootCause(e));
      }catch (Exception e) {
         //get the stack trace in string format
         System.out.println(Throwables.getStackTraceAsString(e));				
      }

      try {
         tester.showcaseThrowables1();			
      }catch (Exception e) {
         System.out.println(Throwables.getStackTraceAsString(e));				
      }
   }

   public void showcaseThrowables() throws InvalidInputException{
      try {
         sqrt(-3.0);			
      } catch (Throwable e) {
         //check the type of exception and throw it
         Throwables.propagateIfInstanceOf(e, InvalidInputException.class);		
         Throwables.propagate(e);
      }	
   }

   public void showcaseThrowables1(){
      try {			
         int[] data = {1,2,3}; 
         getValue(data, 4);			
      } catch (Throwable e) {        
         Throwables.propagateIfInstanceOf(e, IndexOutOfBoundsException.class);		
         Throwables.propagate(e);
      }	
   }

   public double sqrt(double input) throws InvalidInputException{
      if(input < 0) throw new InvalidInputException();
      return Math.sqrt(input);
   }

   public double getValue(int[] list, int index) throws IndexOutOfBoundsException {
      return list[index];
   }

   public void dummyIO() throws IOException {
      throw new IOException();
   }
}

class InvalidInputException extends Exception {
}

第八章 Guava集合工具

在这里插入图片描述

第九章 Guava缓存工具

Guava通过接口LoadingCache提供了一个非常强大的基于内存的LoadingCache<K,V>。在缓存中自动加载值,它提供了许多实用的方法,在有缓存需求时非常有用。

接口声明

@Beta
@GwtCompatible
public interface LoadingCache<K,V> extends Cache<K,V>, Function<K,V>

接口方法

在这里插入图片描述

案例

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.base.MoreObjects;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;

public class GuavaTester {
   public static void main(String args[]){
      //create a cache for employees based on their employee id
      LoadingCache employeeCache = 
         CacheBuilder.newBuilder()
            .maximumSize(100) // maximum 100 records can be cached
            .expireAfterAccess(30, TimeUnit.MINUTES) // cache will expire after 30 minutes of access
            .build(new CacheLoader(){ // build the cacheloader
               @Override
               public Employee load(String empId) throws Exception {
                  //make the expensive call
                  return getFromDatabase(empId);
               }							
            });

      try {			
         //on first invocation, cache will be populated with corresponding
         //employee record
         System.out.println("Invocation #1");
         System.out.println(employeeCache.get("100"));
         System.out.println(employeeCache.get("103"));
         System.out.println(employeeCache.get("110"));
         //second invocation, data will be returned from cache
         System.out.println("Invocation #2");
         System.out.println(employeeCache.get("100"));
         System.out.println(employeeCache.get("103"));
         System.out.println(employeeCache.get("110"));

      } catch (ExecutionException e) {
         e.printStackTrace();
      }
   }

   private static Employee getFromDatabase(String empId){
      Employee e1 = new Employee("Mahesh", "Finance", "100");
      Employee e2 = new Employee("Rohan", "IT", "103");
      Employee e3 = new Employee("Sohan", "Admin", "110");

      Map database = new HashMap();
      database.put("100", e1);
      database.put("103", e2);
      database.put("110", e3);
      System.out.println("Database hit for" + empId);
      return database.get(empId);		
   }
}

class Employee {
   String name;
   String dept;
   String emplD;

   public Employee(String name, String dept, String empID){
      this.name = name;
      this.dept = dept;
      this.emplD = empID;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getDept() {
      return dept;
   }
   public void setDept(String dept) {
      this.dept = dept;
   }
   public String getEmplD() {
      return emplD;
   }
   public void setEmplD(String emplD) {
      this.emplD = emplD;
   }

   @Override
   public String toString() {
      return MoreObjects.toStringHelper(Employee.class)
      .add("Name", name)
      .add("Department", dept)
      .add("Emp Id", emplD).toString();
   }	
}

第十章 Guava字符串工具

在这里插入图片描述

第十一章 Guava数学工具

在这里插入图片描述


总结

Guava的好处在于标准化 - Guava库是由谷歌托管;高效 - 可靠,快速和有效的扩展JAVA标准库;优化 -Guava库经过高度的优化;函数式编程 -增加JAVA功能和处理能力;实用程序 - 提供了经常需要在应用程序开发的许多实用程序类;验证 -提供标准的故障安全验证机制;最佳实践 - 强调最佳的做法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值