学习 Guava(二):基本工具

字符串工具

Joiner

合并 Array 🌰:

Object[] array = {"Tom", null, 12, new Date()};  
Joiner.on(",") // ①  
    .useForNull("null") // ②
    .join(array);
// Tom,null,12,Sat Apr 28 17:21:15 CST 2018

① 分隔符

② useForNull 遇到 null 值使用何值,skipNulls 跳过 null 值

合并 Map 🌰:

Map<Object, Object> map = new HashMap<>();  
map.put("name", "Tom");  
map.put("age", 12);  
Joiner.on("#")  
    .withKeyValueSeparator("=") // ①
    .join(map);
// name=Tom#age=12

① 键值分隔符

Splitter

Splitter.on("|") // ①  
    .trimResults() // ②
    .omitEmptyStrings() // ③
    .split("1|  2||3||4")
// ["1","2","3","4"]

① 分隔符,支持字符、字符串和正则表达式

② 移除字符串前后空格

③ 忽略空字符串

Charsets

byte[] bytes = "我是 Dyingbleed".getBytes(Charsets.UTF_8); // ①  

① 返回 UTF-8 编码的字节数组

Strings

如果为 null 值返回空字符串:

Strings.nullToEmpty(null) // ""  

是否为 null 值或空字符串:

Strings.isNullOrEmpty("") // true  
Strings.isNullOrEmpty(null) // true  

前提条件检查工具

前提条件(Preconditions)工具提供了静态函数,检查条件是否满足,否则抛出异常。

静态引入 Preconditions:

import static com.google.common.base.Preconditions.*;  

检查参数:

checkArgument(args.length < 2, "请输入至少 2 个参数");  

检查状态:

checkState(Runtime.getRuntime().availableProcessors() > 16, "需要至少 16 核 CPU")  

非空检查:

checkNotNull(conf.get("host"), "配置 host 不能为空")  

元素检查:

List<String> list = Splitter.on(",").splitToList("Tom,18,male");  
checkElementIndex(2, list.size(), "无法获取性别字段");  

Object 工具

equals 和 hashCode

public class Book {

    private String name;

    private String author;

    private double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return Double.compare(book.price, price) == 0 &&
                Objects.equal(name, book.name) &&
                Objects.equal(author, book.author);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(name, author, price);
    }
}

compare

public class Book implements Comparable<Book> { // ①

    private String name;

    private String author;

    private double price;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return Double.compare(book.price, price) == 0 &&
                Objects.equal(name, book.name) &&
                Objects.equal(author, book.author);
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(name, author, price);
    }

    @Override
    public int compareTo(Book b) { // ②
        return ComparisonChain.start()
                .compare(this.price, b.price)
                .result();
    }
}

① 实现 Comparable 接口

② 以 ComparisonChain.start() 开始,以 .result() 结尾,调用 compare 方法比较与大小相关的字段,例如:图书的价格

参考