JAVA 工具类整理

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

查看代码
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;
   }	
}
//更多请阅读:https://www.yiibai.com/guava/guava_optional_class.html

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

查看代码
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(排序)可以被看作是一个丰富的比较具有增强功能的链接,多个实用方法,多类型排序功能等。

查看代码
package org.example;

import com.google.common.collect.Ordering;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class GuavaTester {
    public static void main(String args[]){
        List<Integer> numbers = new ArrayList<Integer>();
        numbers.add(5);
        numbers.add(2);
        numbers.add(15);
        numbers.add(51);
        numbers.add(53);
        numbers.add(35);
        numbers.add(45);
        numbers.add(32);
        numbers.add(43);
        numbers.add(16);

        Ordering ordering = Ordering.natural();
        System.out.println("Input List: "+numbers);

        Collections.sort(numbers,ordering );
        System.out.println("SortedList: "+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: "+numbers);

        Collections.sort(numbers,ordering.nullsFirst());
        System.out.println("Null first Sorted List:    "+numbers);
        Collections.sort(numbers,ordering.nullsLast());
        System.out.println("Null last Sorted List:     "+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: "+names);

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

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

查看代码
 package org.example;

import com.google.common.base.MoreObjects;
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(
                MoreObjects.toStringHelper(s1)
                        .add("Name",s1.getFirstName()+" " + s1.getLastName())
                        .add("Class", s1.getClassName())
                        .add("Roll No", s1.getRollNo()));
    }
}

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 表示一个间隔或一个序列。它被用于获取一组数字/串在一个特定范围之内。

查看代码
 package org.example;

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接口的实用方法。

查看代码
 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集合工具:
Multiset:一个扩展来设置界面,允许重复的元素。
Multimap:一个扩展来映射接口,以便其键可一次被映射到多个值
BiMap:一个扩展来映射接口,支持反向操作。
Table:表代表一个特殊的图,其中两个键可以在组合的方式被指定为单个值。

查看代码
 package org.example;

import com.google.common.collect.*;

import java.util.*;

public class GuavaTester {

    public static void main(String[] args) {
        multisetTest();
        System.out.println("“====================================”");
        multimapTest();
        System.out.println("“====================================”");
        bimapTest();
        System.out.println("“====================================”");
        tableTest();
    }

    //<editor-fold desc="1.multiset">
    public static void multisetTest() {
        //create a multiset collection
        Multiset<String> multiset = HashMultiset.create();
        multiset.add("a");
        multiset.add("b");
        multiset.add("c");
        multiset.add("d");
        multiset.add("a");
        multiset.add("b");
        multiset.add("c");
        multiset.add("b");
        multiset.add("b");
        multiset.add("b");
        //print the occurrence of an element
        System.out.println("Occurrence of 'b' : " + multiset.count("b"));
        //print the total size of the multiset
        System.out.println("Total Size : " + multiset.size());
        //get the distinct elements of the multiset as set
        Set<String> set = multiset.elementSet();
        //display the elements of the set
        System.out.print("Set [ ");
        for (String s : set) {
            System.out.print(s + " ");
        }
        System.out.println(" ]");
        //display all the elements of the multiset using iterator
        Iterator<String> iterator = multiset.iterator();
        System.out.print("MultiSet [ ");
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
        System.out.println(" ]");
        //display the distinct elements of the multiset with their occurrence count
        System.out.print("MultiSet [ ");
        for (Multiset.Entry<String> entry : multiset.entrySet()) {
            System.out.print("Element: " + entry.getElement() + ", Occurrence(s): " + entry.getCount() + ";");
        }
        System.out.println(" ]");

        //remove extra occurrences 
        multiset.remove("b", 2);
        //print the occurrence of an element
        System.out.println("Occurrence of 'b' after remove 2: " + multiset.count("b"));
    }
    //</editor-fold>

    //<editor-fold desc="2.multimap">
    public static void multimapTest() {
        Multimap<String, String> multimap = multisetTestgetMultimap();

        List<String> lowerList = (List<String>) multimap.get("lower");
        System.out.println("Initial lower case list: " + lowerList);
        lowerList.add("f");
        System.out.println("Modified lower case list,add f: " + lowerList);

        List<String> upperList = (List<String>) multimap.get("upper");
        System.out.println("Initial upper case list: " + upperList);
        upperList.remove("D");
        System.out.println("Modified upper case list,remove D: " + upperList);

        Map<String, Collection<String>> map = multimap.asMap();
        System.out.print("Multimap as a map: ");
        for (Map.Entry<String, Collection<String>> entry : map.entrySet()) {
            String key = entry.getKey();
            Collection<String> value = multimap.get("lower");
            System.out.print(key + ":" + value + ";");
        }

        System.out.print("\nKeys of Multimap: ");
        Set<String> keys = multimap.keySet();
        for (String key : keys) {
            System.out.print(key + ";");
        }

        System.out.print("\nValues of Multimap: ");
        Collection<String> values = multimap.values();
        System.out.println(values);
    }

    private static Multimap<String, String> multisetTestgetMultimap() {
        //Map<String, List<String>>
        // lower -> a, b, c, d, e
        // upper -> A, B, C, D

        Multimap<String, String> multimap = ArrayListMultimap.create();

        multimap.put("lower", "a");
        multimap.put("lower", "b");
        multimap.put("lower", "c");
        multimap.put("lower", "d");
        multimap.put("lower", "e");

        multimap.put("upper", "A");
        multimap.put("upper", "B");
        multimap.put("upper", "C");
        multimap.put("upper", "D");
        return multimap;
    }

    //</editor-fold>

    //<editor-fold desc="3.bimapTest">
    public static void bimapTest() {
        BiMap<Integer, String> empIDNameMap = HashBiMap.create();

        empIDNameMap.put(101, "Mahesh");
        empIDNameMap.put(102, "Sohan");
        empIDNameMap.put(103, "Ramesh");

        //Emp Id of Employee "Mahesh"
        System.out.println(empIDNameMap.inverse().get("Mahesh"));
    }

    //</editor-fold>

    //<editor-fold desc="4.tableTest">
    public static void tableTest() {
        //Table<R,C,V> == Map<R,Map<C,V>>
        /*
         *  Company: IBM, Microsoft, TCS
         *  IBM 		-> {101:Mahesh, 102:Ramesh, 103:Suresh}
         *  Microsoft 	-> {101:Sohan, 102:Mohan, 103:Rohan }
         *  TCS 		-> {101:Ram, 102: Shyam, 103: Sunil }
         *
         * */
        //create a table
        Table<String, String, String> employeeTable = HashBasedTable.create();

        //initialize the table with employee details
        employeeTable.put("IBM", "101", "Mahesh");
        employeeTable.put("IBM", "102", "Ramesh");
        employeeTable.put("IBM", "103", "Suresh");

        employeeTable.put("Microsoft", "111", "Sohan");
        employeeTable.put("Microsoft", "112", "Mohan");
        employeeTable.put("Microsoft", "113", "Rohan");

        employeeTable.put("TCS", "121", "Ram");
        employeeTable.put("TCS", "122", "Shyam");
        employeeTable.put("TCS", "123", "Sunil");

        //get Map corresponding to IBM
        Map<String, String> ibmEmployees = employeeTable.row("IBM");

        System.out.print("List of IBM Employees: ");
        for (Map.Entry<String, String> entry : ibmEmployees.entrySet()) {
            System.out.print("Emp Id: " + entry.getKey() + ", Name: " + entry.getValue() + ";");
        }

        //get all the unique keys of the table
        Set<String> employers = employeeTable.rowKeySet();
        System.out.print("\nEmployers: ");
        for (String employer : employers) {
            System.out.print(employer + " ");
        }
        System.out.println();

        //get a Map corresponding to 102
        Map<String, String> EmployerMap = employeeTable.column("102");
        for (Map.Entry<String, String> entry : EmployerMap.entrySet()) {
            System.out.println("Employer: " + entry.getKey() + ", Name: " + entry.getValue());
        }
    }
    //</editor-fold>


}

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

 

查看代码
 package org.example;

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

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

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<String, Employee>() { // build the cache loader
                    @Override
                    public Employee load(String empId) {
                        //make the expensive call
                        return getFromDatabase(empId);
                    }
                });

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

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

    private static Employee getFromDatabase(String empId) {
        Map database = new HashMap();
        database.put("100", new Employee("Mahesh", "Finance", "100"));
        database.put("103", new Employee("Rohan", "IT", "103"));
        database.put("110", new Employee("Sohan", "Admin", "110"));
        System.out.print("Database hit for:" + empId + " =>");
        return (Employee) database.get(empId);
    }
}

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

Guava字符串工具:Guava介绍基于开发者的应用开发经验,许多先进的字符串工具。以下是有用的基于字符串的实用程序列表:
Joiner 提供了各种方法来处理字符串加入操作,对象等。
Splitter 提供了各种方法来处理分割操作字符串,对象等。
CharMatcher提供了各种方法来处理各种JAVA char类型值。
CaseFormat是一种实用工具类,以提供不同的ASCII字符格式之间的转换。

查看代码
 package org.example;

import com.google.common.base.CaseFormat;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.base.CharMatcher;

import java.util.Arrays;

public class GuavaTester {
    public static void main(String[] args) {
        GuavaTester tester = new GuavaTester();
        tester.testJoiner();
        System.out.println("=====================================");
        tester.testSplitter();
        System.out.println("=====================================");
        tester.testCharMatcher();
        System.out.println("=====================================");
        tester.testCaseFormat();
    }

    private void testJoiner() {
        System.out.println(Joiner.on(",")
                .skipNulls()
                .join(Arrays.asList(1, 2, 3, 4, 5, null, 6)));
    }

    private void testSplitter() {
        System.out.println(Splitter.on(',')
                .trimResults()
                .omitEmptyStrings()
                .split("the ,quick, , brown         , fox,              jumps, over, the, lazy, little dog."));
    }

    private void testCharMatcher(){
        System.out.println(CharMatcher.digit().retainFrom("mahesh123")); // only the digits
        System.out.println(CharMatcher.inRange('0','9').retainFrom("mahesh123")); // only the digits
        System.out.println(CharMatcher.whitespace().trimAndCollapseFrom("     Mahesh     Parashar ", ' '));
        // trim whitespace at ends, and replace/collapse whitespace into single spaces
        System.out.println(CharMatcher.javaDigit().replaceFrom("mahesh123", "*")); // star out all digits
        System.out.println(CharMatcher.javaDigit().or(CharMatcher.javaLowerCase()).retainFrom("TESTmahesh123"));
        // eliminate all characters that aren't digits or lowercase
    }
    private void testCaseFormat(){
        String data = "test_data";
        System.out.println(CaseFormat.LOWER_HYPHEN.to(CaseFormat.LOWER_CAMEL, "test-data"));
        System.out.println(CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, data));
        System.out.println(CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.UPPER_CAMEL, data));
    }
}

Guava原语工具:作为Java的原语类型,不能用来传递在泛型或于类别作为输入。Guava提供大量包装工具类来处理原始类型的对象。以下是有用的原始处理工具的列表:
Guava Bytes类:Bytes是byte的基本类型实用工具类。
Guava Shorts类:Shorts是基本类型short的实用工具类。
Guava Ints类:整数Ints是原始的int类型的实用工具类。
Guava Longs类:Longs是基本类型long的实用工具类。
Guava Floats类:Floats是float基本类型的实用工具类。
Guava Doubles类:Doubles是double基本类型的实用工具类。
Guava Chars类:Chars是基本char类型的实用工具类。
Guava Booleans类:Booleans是布尔型基本的实用工具类。

查看代码
 package org.example;

import com.google.common.primitives.*;

import java.text.DecimalFormat;
import java.util.List;

public class GuavaTester {
    public static void main(String[] args) {
        GuavaTester tester = new GuavaTester();
        tester.testBytes();
        System.out.println("=============================");
        tester.testShorts();
        System.out.println("=============================");
        tester.testInts();
        System.out.println("=============================");
        tester.testLongs();
        System.out.println("=============================");
        tester.testFloats();
        System.out.println("=============================");
        tester.testDoubles();
        System.out.println("=============================");
        tester.testChars();
        System.out.println("=============================");
        tester.testBooleans();
    }

    private void testBytes() {
        byte[] byteArray = {1, 2, 3, 4, 5, 5, 7, 9, 9};

        //convert array of primitives to array of objects
        List<Byte> objectArray = Bytes.asList(byteArray);
        System.out.println(objectArray);

        //convert array of objects to array of primitives
        byteArray = Bytes.toArray(objectArray);
        System.out.print("[ ");
        for (int i = 0; i < byteArray.length; i++) {
            System.out.print(byteArray[i] + " ");
        }
        System.out.println("]");
        byte data = 5;
        //check if element is present in the list of primitives or not
        System.out.println("5 is in list? " + Bytes.contains(byteArray, data));

        //Returns the index
        System.out.println("Index of 5: " + Bytes.indexOf(byteArray, data));

        //Returns the last index maximum
        System.out.println("Last index of 5: " + Bytes.lastIndexOf(byteArray, data));
    }

    private void testShorts() {
        short[] shortArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        //convert array of primitives to array of objects
        List<Short> objectArray = Shorts.asList(shortArray);
        System.out.println(objectArray);

        //convert array of objects to array of primitives
        shortArray = Shorts.toArray(objectArray);
        System.out.print("[ ");
        for (short value : shortArray) {
            System.out.print(value + " ");
        }
        System.out.println("]");
        short data = 5;
        //check if element is present in the list of primitives or not
        System.out.println("5 is in list? " + Shorts.contains(shortArray, data));

        //Returns the minimum
        System.out.println("Min: " + Shorts.min(shortArray));

        //Returns the maximum
        System.out.println("Max: " + Shorts.max(shortArray));
        data = 2400;
        //get the byte array from an integer
        byte[] byteArray = Shorts.toByteArray(data);
        for (byte b : byteArray) {
            System.out.print(b + " ");
        }
        DecimalFormat decimalFormat = new DecimalFormat("0000000000000000");
        System.out.printf(";2400 hex: 0x%x,0b%16s,%sb,00001001_01100000b=9,96%n", data, Integer.toBinaryString(data), decimalFormat.format(Long.valueOf(Integer.toBinaryString(data))));
    }

    private void testInts() {
        int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        //convert array of primitives to array of objects
        List<Integer> objectArray = Ints.asList(intArray);
        System.out.println(objectArray);

        //convert array of objects to array of primitives
        intArray = Ints.toArray(objectArray);
        System.out.print("[ ");
        for (int i = 0; i < intArray.length; i++) {
            System.out.print(intArray[i] + " ");
        }
        System.out.println("]");
        //check if element is present in the list of primitives or not
        System.out.println("5 is in list? " + Ints.contains(intArray, 5));

        //Returns the minimum
        System.out.println("Min: " + Ints.min(intArray));

        //Returns the maximum
        System.out.println("Max: " + Ints.max(intArray));

        Integer data = 20000;
        //get the byte array from an integer
        byte[] byteArray = Ints.toByteArray(data);
        for (int i = 0; i < byteArray.length; i++) {
            System.out.print(byteArray[i] + " ");
        }
        DecimalFormat decimalFormat = new DecimalFormat("00000000000000000000000000000000");
        System.out.printf(";20000 hex: 0x%x,0b%32s,%sb,01001110_00100000=78,32%n", data, Integer.toBinaryString(data), decimalFormat.format(Long.valueOf(Integer.toBinaryString(data))));
    }

    private void testLongs() {
        long[] longArray = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        //convert array of primitives to array of objects
        List<Long> objectArray = Longs.asList(longArray);
        System.out.println(objectArray);

        //convert array of objects to array of primitives
        longArray = Longs.toArray(objectArray);
        System.out.print("[ ");
        for (int i = 0; i < longArray.length; i++) {
            System.out.print(longArray[i] + " ");
        }
        System.out.println("]");
        //check if element is present in the list of primitives or not
        System.out.println("5 is in list? " + Longs.contains(longArray, 5));

        //Returns the minimum
        System.out.println("Min: " + Longs.min(longArray));

        //Returns the maximum
        System.out.println("Max: " + Longs.max(longArray));

        Long data = 20000L;
        //get the byte array from an integer
        byte[] byteArray = Longs.toByteArray(20000);
        for (byte b : byteArray) {
            System.out.print(b + " ");
        }
        System.out.printf(";20000 hex: 0x%x,0b%64s,01001110_00100000b=78,32%n", data, Long.toBinaryString(data));
    }

    private void testFloats() {
        float[] floatArray = {1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f};

        //convert array of primitives to array of objects
        List<Float> objectArray = Floats.asList(floatArray);
        System.out.println(objectArray);

        //convert array of objects to array of primitives
        floatArray = Floats.toArray(objectArray);
        System.out.print("[ ");
        for (int i = 0; i < floatArray.length; i++) {
            System.out.print(floatArray[i] + " ");
        }
        System.out.println("]");
        //check if element is present in the list of primitives or not
        System.out.println("5.0 is in list? " + Floats.contains(floatArray, 5.0f));

        //return the index of element
        System.out.println("5.0 position in list " + Floats.indexOf(floatArray, 5.0f));

        //Returns the minimum
        System.out.println("Min: " + Floats.min(floatArray));

        //Returns the maximum
        System.out.println("Max: " + Floats.max(floatArray));
    }

    private void testDoubles() {
        double[] doubleArray = {1.0d, 2.0, 3.0, 4.0d, 5.0, 6.0D, 7.0F, 8.0f, 9.0};

        //convert array of primitives to array of objects
        List<Double> objectArray = Doubles.asList(doubleArray);
        System.out.println(objectArray);

        //convert array of objects to array of primitives
        doubleArray = Doubles.toArray(objectArray);
        System.out.print("[ ");
        for (int i = 0; i < doubleArray.length; i++) {
            System.out.print(doubleArray[i] + " ");
        }
        System.out.println("]");
        //check if element is present in the list of primitives or not
        System.out.println("5.0 is in list? " + Doubles.contains(doubleArray, 5.0f));

        //return the index of element
        System.out.println("5.0 position in list " + Doubles.indexOf(doubleArray, 5.0d));

        //Returns the minimum
        System.out.println("Min: " + Doubles.min(doubleArray));

        //Returns the maximum
        System.out.println("Max: " + Doubles.max(doubleArray));
    }

    private void testChars() {
        char[] charArray = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};

        //convert array of primitives to array of objects
        List<Character> objectArray = Chars.asList(charArray);
        System.out.println(objectArray);

        //convert array of objects to array of primitives
        charArray = Chars.toArray(objectArray);
        System.out.print("[ ");
        for (int i = 0; i < charArray.length; i++) {
            System.out.print(charArray[i] + " ");
        }
        System.out.println("]");
        //check if element is present in the list of primitives or not
        System.out.println("c is in list? " + Chars.contains(charArray, 'c'));

        //return the index of element
        System.out.println("c position in list " + Chars.indexOf(charArray, 'c'));

        //Returns the minimum
        System.out.println("Min: " + Chars.min(charArray));

        //Returns the maximum
        System.out.println("Max: " + Chars.max(charArray));
    }

    private void testBooleans() {
        boolean[] booleanArray = {true, true, false, true, true, false, false};

        //convert array of primitives to array of objects
        List<Boolean> objectArray = Booleans.asList(booleanArray);
        System.out.println(objectArray);

        //convert array of objects to array of primitives
        booleanArray = Booleans.toArray(objectArray);
        System.out.print("[ ");
        for (boolean b : booleanArray) {
            System.out.print(b + " ");
        }
        System.out.println("]");
        //check if element is present in the list of primitives or not
        System.out.println("true is in list? " + Booleans.contains(booleanArray, true));

        //return the first index of element
        System.out.println("true position in list :" + Booleans.indexOf(booleanArray, true));

        //Returns the count of true values
        System.out.println("true occurred (): " + Booleans.countTrue());
        System.out.println("true occurred in booleanArray: " + Booleans.countTrue(booleanArray));

        //Returns the comparisons
        System.out.println("false Vs true: " + Booleans.compare(false, true));
        System.out.println("false Vs false: " + Booleans.compare(false, false));
        System.out.println("true Vs false: " + Booleans.compare(true, false));
        System.out.println("true Vs true: " + Booleans.compare(true, true));
    }


}
Guava数学工具:提供Guava数学相关的实用工具类来处理int,long及BigInteger。以下是有用的工具列表:
Guava IntMath类:IntMath提供整型的实用方法。
Guava LongMath类:LongMath提供long基础类型的实用方法。
Guava BigIntegerMath类:BigIntegerMath提供BigInteger的实用方法。
查看代码
 package org.example;

import com.google.common.math.BigIntegerMath;
import com.google.common.math.IntMath;
import com.google.common.math.LongMath;

import java.math.BigInteger;
import java.math.RoundingMode;

public class GuavaTester {

    public static void main(String[] args) {
        GuavaTester tester = new GuavaTester();
        tester.testIntMath();
        System.out.println("======================");
        tester.testLongMath();
        System.out.println("======================");
        tester.testBigIntegerMath();
    }

    private void testIntMath() {
        try {
            System.out.println(IntMath.checkedAdd(Integer.MAX_VALUE, Integer.MAX_VALUE));
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException 0x7fffffff + 0x7fffffff Error: " + e.getMessage());
        }

        System.out.println("100 / 5  舍入模式(UNNECESSARY): " + IntMath.divide(100, 5, RoundingMode.UNNECESSARY));
        try {
            //exception will be thrown as 100 is not completely divisible by 3 thus rounding
            // is required, and RoundingMode is set as UNNESSARY
            System.out.println(IntMath.divide(100, 3, RoundingMode.UNNECESSARY));
        } catch (ArithmeticException e) {
            System.out.println("100 / 3 when RoundingMode=UNNECESSARY Error: " + e.getMessage());
        }
        System.out.println("100 / 3 when RoundingMode=HALF_EVEN: " + IntMath.divide(100, 3, RoundingMode.HALF_EVEN));
        //即四舍六入五考虑,五后非零就进一,五后为零看奇偶,五前为偶应舍去,五前为奇要进一。不明白可百度一下 银行家舍入。
        System.out.println("Log2(2): " + IntMath.log2(2, RoundingMode.HALF_EVEN));

        System.out.println("对数 Log10(10): " + IntMath.log10(10, RoundingMode.HALF_EVEN));

        System.out.println("开平方 sqrt(100): " + IntMath.sqrt(IntMath.pow(10, 2), RoundingMode.HALF_EVEN));

        System.out.println("最大公约数 greatest common divisor gcd(100,50): " + IntMath.gcd(100, 50));

        System.out.println("模数 (整除取余)modulus(100,50): " + IntMath.mod(100, 50));

        System.out.println("阶乘 1*2*3*4*5 factorial(5): " + IntMath.factorial(5));
    }

    private void testLongMath() {
        try {
            System.out.println(LongMath.checkedAdd(Long.MAX_VALUE, Long.MAX_VALUE));
        } catch (ArithmeticException e) {
            System.out.println("ArithmeticException 0x7fffffffffffffffL+0x7fffffffffffffffL Error: " + e.getMessage());
        }

        System.out.println(LongMath.divide(100, 5, RoundingMode.UNNECESSARY));
        try {
            //exception will be thrown as 100 is not completely divisible by 3 thus rounding
            // is required, and RoundingMode is set as UNNESSARY
            System.out.println(LongMath.divide(100, 3, RoundingMode.UNNECESSARY));
        } catch (ArithmeticException e) {
            System.out.println("100 / 3 不能除净,但设置了 RoundingMode=UNNECESSARY Error: " + e.getMessage());
        }

        System.out.println("Log2(2): " + LongMath.log2(2, RoundingMode.HALF_EVEN));

        System.out.println("对数Log10(10): " + LongMath.log10(10, RoundingMode.HALF_EVEN));

        System.out.println("开平方(pow(10,2)表示10的2次幂) sqrt(100): " + LongMath.sqrt(LongMath.pow(10, 2), RoundingMode.HALF_EVEN));

        System.out.println("最大公约数(greatest common divisor) gcd(100,50): " + LongMath.gcd(100, 50));

        System.out.println("取模 modulus(100,50): " + LongMath.mod(100, 50));

        System.out.println("阶乘 factorial(5): " + LongMath.factorial(5));
    }

    private void testBigIntegerMath() {
        System.out.println(BigIntegerMath.divide(BigInteger.TEN, new BigInteger("2"), RoundingMode.UNNECESSARY));
        try {
            //exception will be thrown as 100 is not completely divisible by 3 thus rounding
            // is required, and RoundingMode is set as UNNESSARY
            System.out.println(BigIntegerMath.divide(BigInteger.TEN, new BigInteger("3"), RoundingMode.UNNECESSARY));
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }

        System.out.println("Log2(2): " + BigIntegerMath.log2(new BigInteger("2"), RoundingMode.HALF_EVEN));

        System.out.println("Log10(10): " + BigIntegerMath.log10(BigInteger.TEN, RoundingMode.HALF_EVEN));

        System.out.println("sqrt(100): " + BigIntegerMath.sqrt(BigInteger.TEN.multiply(BigInteger.TEN), RoundingMode.HALF_EVEN));

        System.out.println("factorial(5): " + BigIntegerMath.factorial(5));
    }
}

 

posted @ 2023-03-23 11:38  CharyGao  阅读(68)  评论(0编辑  收藏  举报