Guava

Basic Utilities

Using/avoiding null

Optional

Preconditions

Ordering

Creation

Chaining

Application

Object methods

equals

hashCode

toString

compare/compareTo

Throwables

Collections

Immutable collections

New collection types

Multiset

Multimap

BiMap

Table

ClassToInstanceMap

RangeSet

Utility Classes

Iterables

Lists

Sets

Maps

Multisets

Multimaps

Tables

Extension Utilities

Forwarding Decorators

PeekingIterator

AbstractIterator

Caches

Applicability

Population

Eviction

Removal Listeners

Refresh

Timed Eviction

Size Caps

Garbage Collection

Explicit Removals

Features

Statistics

Interruption

Functional Idioms

Obtaining

Using Predicates

Using Functions

Concurrency

ListenableFuture

Service

Using

Implementations

Strings

Joiner

Splitter

CharMatcher

Charsets

Networking

InternetDomainName

Primitives

Primitive arrays

General utilities

Byte conversion

Unsigned support

Ranges

Building

Operations

Discrete Domains

I/O

Closing Resources

Hashing

BloomFilter

EventBus

Math

Integral

Overflow Checking

Floating Point

Reflection

TypeToken

Invokable

Dynamic Proxies

ClassPath

★CharMatcher

// \n\tを削除

str = CharMatcher.JAVA_ISO_CONTROL.removeFrom(sequence);

// 文字と数字を抽出

str = CharMatcher.JAVA_LETTER_OR_DIGIT.retainFrom(sequence);

// 改行→' '

str = CharMatcher.BREAKING_WHITESPACE.replaceFrom(sequence,' ');

str = CharMatcher.JAVA_UPPER_CASE.trimFrom(sequence);

str = CharMatcher.JAVA_UPPER_CASE.trimLeadingFrom(sequence);

str = CharMatcher.JAVA_UPPER_CASE.trimTrailingFrom(sequence);

// 大文字→?

str = CharMatcher.JAVA_UPPER_CASE.collapseFrom(sequence,'?');

// 小文字→?

str = CharMatcher.JAVA_LOWER_CASE.trimAndCollapseFrom(sequence,'?');

Charsets.UTF_8

Charsets.ISO_8859_1

Charsets.US_ASCII

Charsets.UTF_16

Charsets.UTF_16BE

Charsets.UTF_16LE

★IO

JDKと比較

BufferedReader reader

= new BufferedReader(new FileReader( new File("test.txt") ));

BufferedReader reader = Files.newReader(new File("test.txt"), Charsets.UTF_8);

BufferedWriter writer = Files.newWriter(new File("test.txt"), Charsets.UTF_8);

} finally {

if (reader != null) {

try {

reader.close();

} catch (IOException e) {

logger.error("IOException occured", e);

}

}

}

} finally {

//例外が発生してもスローしない

Closeables.closeQuietly(reader);

}

Writer writer = ...;

IOException thrown = null;

try {

writer.write(...);

} catch (IOException e) {

thrown = e;

} finally {

try {

writer.close();

} catch (IOException e) {

if (thrown == null) {

thrown = e;

} else {

logger.error("IOException occured", e);

}

}

}

if (thrown != null) {

throw thrown;

}

Writer writer = ...;

boolean threw = true;

try {

writer.write(...);

threw = false;

} finally {

// threwがfalseの場合、発生した例外をスローする

// threwがtrueの場合、発生した例外をログ出力のみ行う

Closeables.close(writer, threw);

}

staticメソッド

Files.copy(new File("src.txt"), new File("dest.txt"));

Files.move(new File("src.txt"), new File("dest.txt"));

Files.createParentDirs(new File("aaa/bbb/ccc"));

//読み込み

String text = Files.toString(new File("test.txt"), Charsets.UTF_8);

byte[] bytes = Files.toByteArray(new File("test.txt"));

List<String> lines = Files.readLines(new File("test.txt"), Charsets.UTF_8);

//書き出し

Files.write("xxx".getBytes("UTF_8"), new File("test.txt"));

Files.write("xxx", new File("test.txt"), Charsets.UTF_8);

Files.append("xxx", new File("test.txt"), Charsets.UTF_8);

LineProcessor利用

String lines = Files.readLines(new File("test.txt"), Charsets.UTF_8,

new LineProcessor<String>() {

private List<String> lines = Lists.newArrayList();


@Override

public boolean processLine(String line) throws IOException {

if(line.startsWith("a")) {

lines.add(line);

}

return true;

}

@Override

public String getResult() {

return Joiner.on(",").join(lines);

}

}

);

★ListenableFutureについて

ListeningExecutorService executorService = MoreExecutors

.listeningDecorator(Executors.newCachedThreadPool());

final ListenableFuture<Integer> listenableFuture

= executorService.submit(new Callable<Integer>{...});

// 同期

Integer result = listenableFuture.get();

// 非同期:方式1

listenableFuture.addListener(new Runnable() {

@Override

public void run() {

Integer result = listenableFuture.get();

...

}

}, executorService);

// 非同期:方式2

Futures.addCallback(listenableFuture, new FutureCallback<Integer>() {

@Override

public void onSuccess(Integer result) {

...

}

@Override

public void onFailure(Throwable t) {

...

}

});

★Basic

Optional

nullを避けるための仕組み

Optional利用前

private static final Map<String, String> map

= new HashMap<String, String>();

static {

map.put("key1", "xxx");

map.put("key2", null);

}

String val = map.get("key2"); //null

String val = map.get("key3"); //null

Optional利用後

import com.google.common.base.Optional;

private static final Map<String, Optional<String>> map

= new HashMap<String, Optional<String>>();

static {

map.put("key1", Optional.of("xxx"));

map.put("key2", Optional.<String>absent());

}

Optional<String> val = map.get("key2"); //Nothing

System.out.printf("%s%n",

val == null ? "Unknown": val.isPresent() ? val: "Nothing");

Optional<String> val = map.get("key3"); //Unknown

System.out.printf("%s%n",

val == null ? "Unknown": val.isPresent() ? val: "Nothing");

Preconditions

防御的プログラミング

public void print(File file) {

checkState(!this.isClosed(), "message...");

checkNotNull(file, "message...");

checkArgument(file.isFile(), "message...");

checkArgument(file.canRead(), "message...");

checkArgument( list != null, "List must not be null" );

checkArgument( !list.isEmpty(), "List must not be empty" );

checkState( field.isPresent(), "Argument is not initialied" );

...

}

checkElementIndex(index, values.length, "message...");

Object methods

@override

public String toString(){

return Objects.toStringHelper(this).omitNullValues()

.add("x", this.x)

.toString(); // ClassName{x=1}

return Objects.toStringHelper("MyObject")

.add("x", 1)

.toString(); // MyObject{x=1}

}

@override

public int hashCode() {

return Objects.hashCode(title, author);

}

class Person implements Comparable<Person> {

...

public int compareTo(Person that) {

return ComparisonChain.start()

.compare(this.aString, that.aString)

.compare(this.anInt, that.anInt)

.compare(this.anEnum, that.anEnum,

Ordering.natural().nullsLast())

.result();

}

}

Encoding

import com.google.common.io.BaseEncoding;

String input = "...";

byte[] photo = BaseEncoding.base64().decode(input); // Base 64

byte[] photo = BaseEncoding.base64Url().decode(input); // web safe Base64

※Googleからプロフィール画像を取得する場合

https://www.googleapis.com/admin/directory/v1/users/xxx@example.com/photos/thumbnail

★Collections

Immutable collections

防御的コピー

public static final ImmutableSet<String> COLOR_NAMES = ImmutableSet.of(

"red", "blue", "purple");

class Foo {

private Set<Bar> bars;

public Foo(Set<Bar> bars) {

this.bars = ImmutableSet.copyOf(bars);

}

}

final List<String> list = ImmutableList.of("aa", "bb", "cc");

final Map<String, String> map

= ImmutableMap.of("key1", "value1", "key2", "value2");

Map<Integer, String> numbers =

ImmutableMap.<Integer, String>builder()

.put(1, "one")

.put(2, "two")

.build();

New collection types

MultiSet 同じ値を持つことができるSet

MultiMap キーに対する値を複数もつことができるMap(値の管理:ListMultiMapとSetMultiMap)

BiMap キーだけでなく値もユニークさを保証するMap

Table 行と列の構造を持ったコレクション(2次元配列と違い)

ClassToInstanceMap クラスの型をキーにするMap

RangeSet / RangeMap 範囲のコレクション

JDKと比較

if (!map.contains(k)) {

map.put(k, new ArrayList());

}

map.get(k).add(v);

// MultiMap

map.put(k, v);

List<B> blist = new ArrayList<B>(alist.size());

for (A a : alist) {

blist.add(new B(a));

}

List<B> blist = Lists.transform(alist,

new Function<A, B>(){

@Override

public B apply(A a) {

return new B(a);

}

}

);

Map<KeyA, Map<KeyB, Value>> nestedMap = ...

Map<KeyB, Value> innerMap = nestedMap.get(keyA);

Value value;

if (innerMap == null) {

value = null;

} else {

value = innerMap.get(keyB);

}

Table<KeyA, KeyB, Value> table = ...

Value value = table.get(keyA, keyB);

Utility Classes (import com.google.common.collect)

List<Product> products = ...

List<Integer> ids = Lists.transform(products,

new Function<Product, Integer>(){

public Integer apply(Product p) {

return p.getId();

}

});

Map<String, String> map = Maps.newLinkedHashMap();

Map<String, String> map = Maps.newHashMap();

List<Product> products = ...

Map<Integer, Product> productById = Maps.uniqueIndex(products,

new Function<Product, Integer>(){

public Integer apply(Product p) {

return p.getId();

}

});

Iterable<Integer> concatenated = Iterables.concat(

Ints.asList(1, 2, 3),

Ints.asList(4, 5, 6)

);

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

multiSet.add("key");

String theElement = Iterables.getOnlyElement(multiSet);

Iterable<String> i = ...;

String[] array = Iterables.toArray(i, String.class);

List<Product> products = ...

Product p = Iterables.find(products,

new Predicate<Product>(){

public boolean apply(Product p) {

return p.getId() == 101;

}

});

Iterable<Product> filtered = Iterables.filter(products,

new Predicate<Product>(){

public boolean apply(Product p) {

return "sport".equals(p.getCategory());

}

});