Guava – Collections Utilities ”; Previous Next Guava introduces many advanced collections based on developers” experience in application development works. Given below is a list of useful collections − Sr.No Collection name & Description 1 Multiset An extension to Set interface to allow duplicate elements. 2 Multimap An extension to Map interface so that its keys can be mapped to multiple values at a time. 3 BiMap An extension to Map interface to support inverse operations. 4 Table Table represents a special map where two keys can be specified in combined fashion to refer to a single value. Print Page Previous Next Advertisements ”;
Category: guava
Guava – Useful Resources
Guava – Useful Resources ”; Previous Next The following resources contain additional information on Guava. Please use them to get more in-depth knowledge on this topic. Useful Links on Guava Guava – Guava official home page Google Guava – Wiki – Wikipedia reference for Google Guava Library. Useful Books on Guava To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Guava – Caching Utilities
Guava – Caching Utilities ”; Previous Next Guava provides a very powerful memory based caching mechanism by an interface LoadingCache<K,V>. Values are automatically loaded in the cache and it provides many utility methods useful for caching needs. Interface Declaration Following is the declaration for com.google.common.cache.LoadingCache<K,V> interface − @Beta @GwtCompatible public interface LoadingCache<K,V> extends Cache<K,V>, Function<K,V> Interface Methods Sr.No Method & Description 1 V apply(K key) Deprecated. Provided to satisfy the Function interface; use get(K) or getUnchecked(K) instead. 2 ConcurrentMap<K,V> asMap() Returns a view of the entries stored in this cache as a thread-safe map. 3 V get(K key) Returns the value associated with key in this cache, first loading that value if necessary. 4 ImmutableMap<K,V> getAll(Iterable<? extends K> keys) Returns a map of the values associated with keys, creating or retrieving those values if necessary. 5 V getUnchecked(K key) Returns the value associated with key in this cache, first loading that value if necessary. 6 void refresh(K key) Loads a new value for key, possibly asynchronously. Example of LoadingCache Create the following java program using any editor of your choice in say C:/> Guava. GuavaTester.java 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<String, Employee> 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 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<String, Employee> database = new HashMap<String, Employee>(); 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(); } } Verify the Result Compile the class using javac compiler as follows − C:Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:Guava>java GuavaTester See the result. Invocation #1 Database hit for100 Employee{Name=Mahesh, Department=Finance, Emp Id=100} Database hit for103 Employee{Name=Rohan, Department=IT, Emp Id=103} Database hit for110 Employee{Name=Sohan, Department=Admin, Emp Id=110} Invocation #2 Employee{Name=Mahesh, Department=Finance, Emp Id=100} Employee{Name=Rohan, Department=IT, Emp Id=103} Employee{Name=Sohan, Department=Admin, Emp Id=110} Print Page Previous Next Advertisements ”;
Guava – Ordering Class
Guava – Ordering Class ”; Previous Next Ordering can be seen as an enriched comparator with enhanced chaining functionality, multiple utility methods, multi-type sorting capability, etc. Class Declaration Following is the declaration for com.google.common.collect.Ordering<T> class − @GwtCompatible public abstract class Ordering<T> extends Object implements Comparator<T> Class Methods Sr.No Method & Description 1 static Ordering<Object> allEqual() Returns an ordering which treats all values as equal, indicating “no ordering.” Passing this ordering to any stable sort algorithm results in no change to the order of elements. 2 static Ordering<Object> arbitrary() Returns an arbitrary ordering over all objects, for which compare(a, b) == 0 implies a == b (identity equality). 3 int binarySearch(List<? extends T> sortedList, T key) Searches sortedList for key using the binary search algorithm. 4 abstract int compare(T left, T right) Compares its two arguments for order. 5 <U extends T> Ordering<U> compound(Comparator<? super U> secondaryComparator) Returns an ordering which first uses the ordering this, but which in the event of a “tie”, then delegates to secondaryComparator. 6 static <T> Ordering<T> compound(Iterable<? extends Comparator<? super T>> comparators) Returns an ordering which tries each given comparator in order until a non-zero result is found, returning that result, and returning zero only if all comparators return zero. 7 static <T> Ordering<T> explicit(List<T> valuesInOrder) Returns an ordering that compares objects according to the order in which they appear in the given list. 8 static <T> Ordering<T> explicit(T leastValue, T… remainingValuesInOrder) Returns an ordering that compares objects according to the order in which they are given to this method. 9 static <T> Ordering<T> from(Comparator<T> comparator) Returns an ordering based on an existing comparator instance. 10 <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) Returns the k greatest elements of the given iterable according to this ordering, in order from greatest to least. 11 <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) Returns the k greatest elements from the given iterator according to this ordering, in order from greatest to least. 12 <E extends T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements) Returns an immutable list containing elements sorted by this ordering. 13 boolean isOrdered(Iterable<? extends T> iterable) Returns true if each element in iterable after the first is greater than or equal to the element that preceded it, according to this ordering. 14 boolean isStrictlyOrdered(Iterable<? extends T> iterable) Returns true if each element in iterable after the first is strictly greater than the element that preceded it, according to this ordering 15 <E extends T> List<E> leastOf(Iterable<E> iterable, int k) Returns the k least elements of the given iterable according to this ordering, in order from least to greatest. 16 <E extends T> List<E> leastOf(Iterator<E> elements, int k) Returns the k least elements from the given iterator according to this ordering, in order from least to greatest. 17 <S extends T> Ordering<Iterable<S>> lexicographical() Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until a nonzero result is found; imposes “dictionary order”. 18 <E extends T> E max(E a, E b) Returns the greater of the two values according to this ordering. 19 <E extends T> E max(E a, E b, E c, E… rest) Returns the greatest of the specified values according to this ordering. 20 <E extends T> E max(Iterable<E> iterable) Returns the greatest of the specified values according to this ordering. 21 <E extends T> E max(Iterator<E> iterator) Returns the greatest of the specified values according to this ordering. 22 <E extends T> E min(E a, E b) Returns the lesser of the two values according to this ordering. 23 <E extends T> E min(E a, E b, E c, E… rest) Returns the least of the specified values according to this ordering. 24 <E extends T> E min(Iterable<E> iterable) Returns the least of the specified values according to this ordering. 25 <E extends T> E min(Iterator<E> iterator) Returns the least of the specified values according to this ordering. 26 static <C extends Comparable> Ordering<C> natural() Returns a serializable ordering that uses the natural order of the values. 27 <S extends T> Ordering<S> nullsFirst() Returns an ordering that treats null as less than all other values and uses this to compare non-null values. 28 <S extends T> Ordering<S> nullsLast() Returns an ordering that treats null as greater than all other values and uses this ordering to compare non-null values. 29 <F> Ordering<F> onResultOf(Function<F,? extends T> function) Returns a new ordering on F which orders elements by first applying a function to them, then comparing those results using this. 30 <S extends T> Ordering<S> reverse() Returns the reverse of this ordering; the Ordering equivalent to Collections.reverseOrder(Comparator). 31 <E extends T> List<E> sortedCopy(Iterable<E> elements) Returns a mutable list containing elements sorted by this ordering; use this only when the resulting list may need further modification, or may contain null. 32 static Ordering<Object> usingToString() Returns an ordering that compares objects by the natural ordering of their string representations as returned by toString(). Methods Inherited This class inherits methods from the following class − java.lang.Object Example of Ordering Class Create the following java program using any editor of your choice in say C:/> Guava. GuavaTester.java 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); } } Verify the Result Compile the class using javac compiler as follows − C:Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:Guava>java GuavaTester
Guava – Optional Class
Guava – Optional Class ”; Previous Next Optional is an immutable object used to contain a not-null object. Optional object is used to represent null with absent value. This class has various utility methods to facilitate the code to handle values as available or not available instead of checking null values. Class Declaration Following is the declaration for com.google.common.base.Optional<T> class − @GwtCompatible(serializable = true) public abstract class Optional<T> extends Object implements Serializable Class Methods Sr.No Method & Description 1 static <T> Optional<T> absent() Returns an Optional instance with no contained reference. 2 abstract Set<T> asSet() Returns an immutable singleton Set whose only element is the contained instance if it is present; an empty immutable Set otherwise. 3 abstract boolean equals(Object object) Returns true if object is an Optional instance, and either the contained references are equal to each other or both are absent. 4 static <T> Optional<T> fromNullable(T nullableReference) If nullableReference is non-null, returns an Optional instance containing that reference; otherwise returns absent(). 5 abstract T get() Returns the contained instance, which must be present. 6 abstract int hashCode() Returns a hash code for this instance. 7 abstract boolean isPresent() Returns true if this holder contains a (non-null) instance. 8 static <T> Optional<T> of(T reference) Returns an Optional instance containing the given non-null reference. 9 abstract Optional<T> or(Optional<? extends T> secondChoice) Returns this Optional if it has a value present; secondChoice otherwise. 10 abstract T or(Supplier<? extends T> supplier) Returns the contained instance if it is present; supplier.get() otherwise. 11 abstract T or(T defaultValue) Returns the contained instance if it is present; defaultValue otherwise. 12 abstract T orNull() Returns the contained instance if it is present; null otherwise. 13 static <T> Iterable<T> presentInstances(Iterable<? extends Optional<? extends T>> optionals) Returns the value of each present instance from the supplied optionals, in order, skipping over occurrences of absent(). 14 abstract String toString() Returns a string representation for this instance. 15 abstract <V> Optional<V> transform(Function<? super T,V> function) If the instance is present, it is transformed with the given Function; otherwise, absent() is returned. Methods Inherited This class inherits methods from the following class − java.lang.Object Example of Optional Class Create the following java program using any editor of your choice in say C:/> Guava. GuavaTester.java 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; } } Verify the Result Compile the class using javac compiler as follows − C:Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:Guava>java GuavaTester See the result. First parameter is present: false Second parameter is present: true 10 Print Page Previous Next Advertisements ”;
Guava – Overview
Guava – Overview ”; Previous Next What is Guava? Guava is an open source, Java-based library and contains many core libraries of Google, which are being used in many of their projects. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations. Benefits of Guava Standardized − The Guava library is managed by Google. Efficient − It is a reliable, fast, and efficient extension to the Java standard library. Optimized − The library is highly optimized. Functional Programming − It adds functional processing capability to Java. Utilities − It provides many utility classes which are regularly required in programming application development. Validation − It provides a standard failsafe validation mechanism. Best Practices − It emphasizes on best practices. Consider the following code snippet. public class GuavaTester { public static void main(String args[]) { GuavaTester guavaTester = new GuavaTester(); Integer a = null; Integer b = new Integer(10); System.out.println(guavaTester.sum(a,b)); } public Integer sum(Integer a, Integer b) { return a + b; } } Run the program to get the following result. Exception in thread “main” java.lang.NullPointerException at GuavaTester.sum(GuavaTester.java:13) at GuavaTester.main(GuavaTester.java:9) Following are the problems with the code. sum() is not taking care of any of the parameters to be passed as null. caller function is also not worried about passing a null to the sum() method accidently. When the program runs, NullPointerException occurs. In order to avoid the above problems, null check is to be made in each and every place where such problems are present. Let”s see the use of Optional, a Guava provided Utility class, to solve the above problems in a standardized way. import com.google.common.base.Optional; public class GuavaTester { public static void main(String args[]) { GuavaTester guavaTester = new GuavaTester(); Integer invalidInput = null; Optional<Integer> a = Optional.of(invalidInput); Optional<Integer> b = Optional.of(new Integer(10)); System.out.println(guavaTester.sum(a,b)); } public Integer sum(Optional<Integer> a, Optional<Integer> b) { return a.get() + b.get(); } } Run the program to get the following result. Exception in thread “main” java.lang.NullPointerException at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:210) at com.google.common.base.Optional.of(Optional.java:85) at GuavaTester.main(GuavaTester.java:8) Let”s understand the important concepts of the above program. Optional − A utility class, to make the code use the null properly. Optional.of − It returns the instance of Optional class to be used as a parameter. It checks the value passed, not to be ‘null’. Optional.get − It gets the value of the input stored in the Optional class. Using the Optional class, you can check whether the caller method is passing a proper parameter or not. Print Page Previous Next Advertisements ”;
Guava – Discussion
Discuss Guava ”; Previous Next Guava is an open source, Java-based library developed by Google. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations. This tutorial adopts a simple and intuitive way to describe the basic-to-advanced concepts of Guava and how to use its APIs. Print Page Previous Next Advertisements ”;
Guava – Math Utilities
Guava – Math Utilities ”; Previous Next Guava provides Mathematics related Utilities classes to handle int, long and BigInteger. Following is the list of useful utilities − Sr.No Utility name & Description 1 IntMath Math utility for int. 2 LongMath Math utility for long. 3 BigIntegerMath Math utility for BigInteger. Print Page Previous Next Advertisements ”;
Guava – Preconditions Class
Guava – Preconditions Class ”; Previous Next Preconditions provide static methods to check that a method or a constructor is invoked with proper parameter or not. It checks the pre-conditions. Its methods throw IllegalArgumentException on failure. Class Declaration Following is the declaration for com.google.common.base.Preconditions class − @GwtCompatible public final class Preconditions extends Object Class Methods Sr.No Method & Description 1 static void checkArgument(boolean expression) Ensures the truth of an expression involving one or more parameters to the calling method. 2 static void checkArgument(boolean expression, Object errorMessage) Ensures the truth of an expression involving one or more parameters to the calling method. 3 static void checkArgument(boolean expression, String errorMessageTemplate, Object. errorMessageArgs) Ensures the truth of an expression involving one or more parameters to the calling method. 4 static int checkElementIndex(int index, int size) Ensures that index specifies a valid element in an array, list or a string of size. 5 static int checkElementIndex(int index, int size, String desc) Ensures that index specifies a valid element in an array, list, or a string of size. 6 static <T> T checkNotNull(T reference) Ensures that an object reference passed as a parameter to the calling method is not null. 7 static <T> T checkNotNull(T reference, Object errorMessage) Ensures that an object reference passed as a parameter to the calling method is not null. 8 static <T> T checkNotNull(T reference, String errorMessageTemplate, Object… errorMessageArgs) Ensures that an object reference passed as a parameter to the calling method is not null. 9 static int checkPositionIndex(int index, int size) Ensures that index specifies a valid position in an array, list or a string of size. 10 static int checkPositionIndex(int index, int size, String desc) Ensures that index specifies a valid position in an array, list or a string of size. 11 static void checkPositionIndexes(int start, int end, int size) Ensures that start and end specify a valid positions in an array, list or a string of size, and are in order. 12 static void checkState(boolean expression) Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method. 13 static void checkState(boolean expression, Object errorMessage) Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method. 14 static void checkState(boolean expression, String errorMessageTemplate, Object… errorMessageArgs) Ensures the truth of an expression involving the state of the calling instance, but not involving any parameters to the calling method. Methods Inherited This class inherits methods from the following class − java.lang.Object Example of Preconditions Class Create the following java program using any editor of your choice in say C:/> Guava. GuavaTester.java 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; } } Verify the Result Compile the class using javac compiler as follows − C:Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:Guava>java GuavaTester See the result. Illegal Argument passed: Negative value -3.0. Illegal Argument passed: First parameter is Null. Illegal Argument passed: Invalid index. (6) must be less than size (5) Print Page Previous Next Advertisements ”;
Guava – Range Class
Guava – Range Class ”; Previous Next Range represents an interval or a sequence. It is used to get a set of numbers/ strings lying in a particular range. Class Declaration Following is the declaration for com.google.common.collect.Range<C> class − @GwtCompatible public final class Range<C extends Comparable> extends Object implements Predicate<C>, Serializable Methods Sr.No Method & Description 1 static <C extends Comparable<?>> Range<C> all() Returns a range that contains every value of type C. 2 boolean apply(C input)Deprecated. Provided only to satisfy the Predicate interface; use contains(C) instead. 3 static <C extends Comparable<?>> Range<C> atLeast(C endpoint) Returns a range that contains all values greater than or equal to endpoint. 4 static <C extends Comparable<?>> Range<C> atMost(C endpoint) Returns a range that contains all values less than or equal to endpoint. 5 Range<C> canonical(DiscreteDomain<C> domain) Returns the canonical form of this range in the given domain. 6 static <C extends Comparable<?>> Range<C> closed(C lower, C upper) Returns a range that contains all values greater than or equal to lower and less than or equal to upper. 7 static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper) Returns a range that contains all values greater than or equal to lower and strictly less than upper. 8 boolean contains(C value) Returns true if value is within the bounds of this range. 9 boolean containsAll(Iterable<? extends C> values) Returns true if every element in values is contained in this range. 10 static <C extends Comparable<?>> Range<C> downTo(C endpoint, BoundType boundType) Returns a range from the given endpoint, which may be either inclusive (closed) or exclusive (open), with no upper bound. 11 static <C extends Comparable<?>> Range<C> encloseAll(Iterable<C> values) Returns the minimal range that contains all of the given values. 12 boolean encloses(Range<C> other) Returns true if the bounds of other do not extend outside the bounds of this range. 13 boolean equals(Object object) Returns true if object is a range having the same endpoints and bound types as this range. 14 static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) Returns a range that contains all values strictly greater than endpoint. 15 int hashCode() Returns a hash code for this range. 16 boolean hasLowerBound() Returns true if this range has a lower endpoint. 17 boolean hasUpperBound() Returns true if this range has an upper endpoint. 18 Range<C> intersection(Range<C> connectedRange) Returns the maximal range enclosed by both this range and connectedRange, if such a range exists. 19 boolean isConnected(Range<C> other) Returns true if there exists a (possibly empty) range which is enclosed by both this range and other. 20 boolean isEmpty() Returns true if this range is of the form [v..v) or (v..v]. 21 static <C extends Comparable<?>> Range<C> lessThan(C endpoint) Returns a range that contains all values strictly less than endpoint. 22 BoundType lowerBoundType() Returns the type of this range”s lower bound: BoundType.CLOSED if the range includes its lower endpoint, BoundType.OPEN if it does not. 23 C lowerEndpoint() Returns the lower endpoint of this range. 24 static <C extends Comparable<?>> Range<C> open(C lower, C upper) Returns a range that contains all values strictly greater than lower and strictly less than upper. 25 static <C extends Comparable<?>> Range<C> openClosed(C lower, C upper) Returns a range that contains all values strictly greater than lower and less than or equal to upper. 26 static <C extends Comparable<?>> Range<C> range(C lower, BoundType lowerType, C upper, BoundType upperType) Returns a range that contains any value from lower to upper, where each endpoint may be either inclusive (closed) or exclusive (open). 27 static <C extends Comparable<?>> Range<C> singleton(C value) Returns a range that contains only the given value. 28 Range<C> span(Range<C> other) Returns the minimal range that encloses both this range and other. 29 String toString() Returns a string representation of this range, such as “[3..5)” (other examples are listed in the class documentation). 30 BoundType upperBoundType() Returns the type of this range”s upper bound: BoundType.CLOSED if the range includes its upper endpoint, BoundType.OPEN if it does not. 31 C upperEndpoint() Returns the upper endpoint of this range. 32 static <C extends Comparable<?>> Range<C> upTo(C endpoint, BoundType boundType) Returns a range with no lower bound up to the given endpoint, which may be either inclusive (closed) or exclusive (open). Methods Inherited This class inherits methods from the following class − java.lang.Object Example of Range Class Create the following java program using any editor of your choice in say C:/> Guava. GuavaTester.java 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(“]”); } } Verify the Result Compile the class using javac compiler as follows − C:Guava>javac GuavaTester.java Now run the GuavaTester to see the result. C:Guava>java GuavaTester See the result. [0,9] : [ 0 1 2 3 4 5 6 7