性感的 Guava

转自:性感的 Guava

What's Guava

Google 的一个开源项目,包含许多 Google 核心的 Java 常用库。

很多类似 Apache Common 的功能,但实现更优雅,项目也更活跃。

试图弥补 Java 语言的不足,很多特性被加入到最新的 Java 语言规范中。

Objects#equal

1

2

3

4


Objects.equal("a", "a"); // return true

Objects.equal(null, "a"); // return false

Objects.equal("a", null); // return false

Objects.equal(null, null); // return true


Java7 引入的 Objects 类提供了一样的方法 Objects.equals。

Objects#hashCode

1

2

3


public int hashCode() {

    return Objects.hashCode(firstName, lastname, address);

}


Java7 引入的 Objects 类提供了一样的方法 Objects.hash(Object...)。

Objects#toString

1

2

3

4

5

6

7


public String toString() {

    return Objects.toStringHelper(this)

            .add("firstName", firstName)

            .add("lastName", lastName)

            .add("age", age)

            .toString();

}




高版本的 Guava 里的 toStringHelper 方法移到了 MoreObjects 里了。

Comparable

1

2

3

4

5

6

7

8


public int compareTo(User that) {

    return CComparisonChain.start()

            .compare(this.firstName, that.firstName)

            .compare(this.lastName, that.lastName)

            .compare(this.age, that.age)

            .compareFalseFirst(this.locked, that.locked)

            .result();

}




PreConditions

1

2

3


//Preconditions.checkNotNull(arg1, "参数 arg1 不正确,不能为空。");

checkNotNull(arg1, "参数 arg1 不正确,不能为空。");

checkArgument(arg2 > 18, "参数 arg2 不正确,值是%s,必须大于18。", arg2);


方法声明描述检查失败时抛出的异常
checkArgument(boolean)检查 boolean 是否为 true,用来检查传递给方法的参数。IllegalArgumentException
checkNotNull(T)检查 value 是否为 null,该方法直接返回 value,因此可以内嵌使用 checkNotNull。NullPointerException
checkState(boolean)用来检查对象的某些状态。IllegalStateException
checkElementIndex(int index, int size)列表、字符串或数组是否有效。index>=0 && index<sizeIndexOutOfBoundsException
checkPositionIndex(int index, int size)检查index作为位置值对某个列表、字符串或数组是否有效。index>=0 && index<=sizeIndexOutOfBoundsException
checkPositionIndexes(int start, int end, int size)检查[start, end]表示的位置范围对某个列表、字符串或数组是否有效IndexOutOfBoundsException

Optional#or

1

2

3

4

5


String username = null;

// String name = username != null ? username ? "游客";

// String name = Objects.firstNonNull(username, "游客");

String name = Optional.of(username).or("游客");

System.out.println(name + "你好!"); // 游客你好!


相当于 JavaScript 中: var a = x || y;

Return null — What's mean?

1

2

3

4

5

6

7


// 可能会返回 null

User user = User.getUserByName("tom");

if(user != null) {

    user.doSomething();

} else {

    admin.doSomething();

}



1

2

3


// 可能会返回 null

Optional<User> user = User.getUserByName("tom");

user.or(admin).doSomething();




Java8 里提供了 Optional:http://blog.jhades.org/java-8-how-to-use-optional/

Strings#split

1

2

3

4

5


Iterable<String> strs = Splitter.on(",")

            .trimResults()

            .omitEmptyStrings()

            .split(",a,,           b,");

System.out.println(strs); // [a, b]




Strings#utils

1

2

3


Strings.padStart("521", 5, '0'); // 00521

Strings.padEnd("33", 4, '#'); // 33##

Strings.repeat("hello ", 3); // hello hello hello




Strings#join

1

2

3

4


Joiner.on(",")

    .skipNulls()

    .join(new String[] {"1", "5", null, "7"});

// return "1,5,7"




CharMatcher

1

2

3

4

5

6

7

8

9

10

11

12

13


// 移除 control 字符

CharMatcher.JAVA_ISO_CONTROL.removeFrom(string);

// 只保留数字字符

CharMatcher.DIGIT.relationFrom(string);

// 去除两端的空格, 并把中间的连续空格替换成单个空格

CharMatcher.WHITESPACE.trimAndCollapseFrom(string, ' ');

// 用*号替换所有数字

CharMatcher.JAVA_DIGIT.replaceFrom(string, '*');

// 只保留数字和小写字母

CharMatcher.JAVA_DIGIT.or(CharMatcher.JAVA_LOWER_CASE).retainFrom(string);


// returns "constantName"

CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "CONSTANT_NAME");




Collection - Multiset

1

2

3

4

5

6


Multiset<String> votes =HashMultiset.create();

votes.add("张三");

votes.add("李四");

votes.add("张三");

int count = votes.count("张三"); // 返回2

Set<String> strings = votes.elementSet(); // 不重复元素的Set




Collection - Multimap

1

2

3

4

5

6

7


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


tags.put("《红楼梦》", "好看");

tags.put("《红楼梦》", "有内容");

tags.put("《红楼梦》", "价格太贵");


tags.put("《水浒》", "打打杀杀");




结构相当于Map<String, List

>但操作更便利。

Collection - Bimap

1

2

3

4

5

6

7


BiMap<String, String> couple = HashBiMap.create();


couple.put("梁山伯", "祝英台");

couple.put("罗密欧", "朱丽叶");


couple.inverse().get("朱丽叶"); // 返回 罗密欧

couple.put("马文才", 祝英台"); // 抛出 IllegalArgumentException 异常




Collection - Table

1

2

3

4

5

6

7

8


Table<String, String, Double> table = HashBasedtable.create();


table.put("张三", "数学", 95.0);

table.put("张三", "语文", 88.5);

table.put("李四", "数学", 90.0);

table.put("李四", "语文", 92.0);


table.get("张三", "数学"); // 返回 95.0






Collection - utils

1

2

3

4


// Java7 里的 List<String> list = new ArrayList<>();

List<String> list1 = Lists.newArrayList();

List<String> list2 = Lists.newArrayList("alpha, "beta", gamma");

List<String> list3 = Lists.newArrayListWithExpectedSize(100);


1

2

3


List countUp = Ints.asList(1, 2, 3, 4, 5);

List countDown = Lists.reverse(countUp); // {5, 4, 3, 2, 1}

List<List> parts = Lists.partition(countUp, 2); // {{1,2}, {3,4}, {5}}


1

2

3

4

5

6

7


Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);

Map<String, Integer> right = ImmutableMap.of("b", 2, "d", 4);

MapDifference<String, Integer> diff = Maps.difference(left, right);


diff.entriesInCommon(); // {"b" => 2}

diff.entriesOnlyOnLeft(); // {"a" => 1, "c" => 3}

diff.entriesOnlyOnRight(); // {"d" => 4}




Collection - Fuctional

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27


boolean hasYoung = Iterables.any(users, new Predicate<User>() {

    @Override

    public boolean apply(@Nullable User user) {

        return user.getAge() < 18;

    }

});


boolean hasYoung = Iterables.all(users, new Predicate<User>() {

    @Override

    public boolean apply(@Nullable User user) {

        return user.getSex() == MALE;

    }

});


boolean hasYoung = Iterables.find(users, new Predicate<User>() {

    @Override

    public boolean apply(@Nullable User user) {

        return "Tom".equals(user.getName());

    }

});


boolean hasYoung = Iterables.removeIf(users.iterator(), new Predicate<User>() {

    @Override

    public boolean apply(@Nullable User user) {

        return user.getAge() > 80;

    }

});




Java8 Stream API

1

2

3

4

5

6

7

8


Optional<String> reduced = stringCollection

        .stream()

        .sorted()

        .reduce((s1, s2) -> s1 + "#" + s2);


reduced.ifPresent(System.out::println);


// "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1"




Supplier

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20


static Supplier<DateAndDuration> yearEndSupplier;

static {

    Supplier<DateAndDuration> supplier = new Supplier<DateAndDuration>() {

        @Override

        public DateAndDuration get() {

            Calendar calendar = Calendar.getInstance();

            int year = calendar.get(Calendar.YEAR);

            calendar.clear();

            calendar.set(year, 11, 31, 23, 59, 59);

            long duration =calendar.getTimeInMills() - new Date().getTime();

            return new dateAndDuration(calendar.getTime(), duration);

        }

    };

    yearEndSupplier = Suppliers.memoizeWithException(supplier, supplier.get()

                            .getDuration(), TimeUnit.MICROSECONDS);

}


public static Date getYearEnd() {

    return yearEndSupplier.get().getDate();

}




Java8 中引入了 Supplier 接口:http://www.byteslounge.com/tutorials/java-8-consumer-and-supplier

Cache

1

2

3

4

5

6

7

8

9

10

11

12


witerCache = CacheBuilder.newBuilder()

            .maximumSize(this.fileCacheSize).removalListener((RemovalListener) {

    try {

        objectObjectRemovalNotification.getValue().flush();

        objectObjectRemovalNotificaiont.getValue().close();

        if(log.isDebugEnabled()) {

            log.debug("释放文件写入的write。");

        }

    } catche(IOException e) {

        log.error("关闭文件出错", e);

    }

}).build();




Other

Math – 最大公约数、各种舍入、指数计算等等

IO – 文件拷贝、URL 访问、遍历文件目录等等 EventBus / 多线程 / Range



转载请并标注: “本文转载自 linkedkeeper.com (文/张松然)”