Google Guava 001 -- Optional, Preconditions, Ordering

 Optional

Optional is an immutable object that may or may not contain a reference to another object, i.e. You can use optional objects to hold null objects.

  • Present = non-null
  • Absent = null

Create Optional Objects

  • Optional.absent() -- Create an optional object that is null

  • Optional.of(T ref) -- Create an optional object that points to object ref
  • Optional.fromNullable(T ref) -- Create an absent fo ref is null; otherwise creates an optional object that points to object ref

When is Optional useful?

A good use case for the Optional class is to have methods that return values which return Optional instead. That way we are forcing clients to consider the fact that the returned value may not be present, and we should take action accordingly.

Optional example

import com.google.common.base.Optional; //import Optional from guava

public class OptionalTest {

	public static void main(String[] args) {
		
		Integer value1 =  null;
        Integer value2 =  10;
        
        Optional<Integer> a = Optional.fromNullable(value1); 
        Optional<Integer> b = Optional.of(value2);
        
        Integer c = a.or(0); //or handles null objects
        Integer d = b.or(0); //Returns the contained instance if it is present; defaultValue otherwise

        
        System.out.println("First parameter is present: " + a.isPresent()); //isPresent checks if a param is present

        System.out.println("Second parameter is present: " + b.isPresent());
        
        System.out.println("Hash code for the second parameter is: " + b.hashCode()); //print hashcode of optional object b

        System.out.println("Value of c is: " + c);
        System.out.println("Value of d is: " + d);
	}

}

Preconditions

Preconditions is a collection of static methods used to verify the state of our code

Example methodes: 

  • checkNotNull (T object, Object message): This method returns the object if it is not null; otherwise a NullPointerException error is thrown.
  • checkElementIndex (int index, int sizeObject message): checks if the index to be access is valid
  • checkArgument (Boolean expression, Object message): This method checks if a Boolean expression evaluates true.
     

Ordering

Ordering class provides us with tools that we need for applying different sorting techniques powerfully and concisely

Declaring an ordering object

  • Use an existing comparator

e.g. static <C extends Comparable> Ordering<C> natural(): Returns a serializable ordering that uses the natural order of the values

Ordering ordering = Ordering.natural();
  • Declare a comparator yourself and use that
public class CityByPopluation implements Comparator<City> {

    @Override
    public int compare(City city1, City city2) {
        return Ints.compare(city1.getPopulation(),city2.getPopulation());
    }
}
Ordering.from(cityByPopluation); //Use from method to specify the comparator you choose

Sort a list with ordering object

List<City> cities = Lists.newArrayList(city1,city2,city3); // Create java list
Ordering<City> Ordering = Ordering.from(cityByPopulation); // Declare ordering object
Collections.sort(cities,Ordering); // sort the list with collections.sort

If you want to reverse the order, you can use

Ordering.from(comparator).reverse();

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值