主要翻译GUAVA的介绍
- 过滤数据,数据验证器
- 通常
在上面需要检查 speed,enginepublic Car(Engine engine) { this.engine = checkNotNull(engine); // NPE } public void drive(double speed) { checkArgument(speed > 0.0, "speed (%s) must be positive", speed); // IAE checkState(engine.isRunning(), "engine must be running"); // ISE ... }
-
return Objects.toStringHelper(this) .add("name", name) .add("id", userId) .add("pet", petName) // petName is @Nullable! .omitNullValues() .toString(); // "Person{name=Kurt Kluever, id=42}" Or without .omitNullValues(): omitNullValues()函数可以过滤空的数据 // "Person{name=Kurt Kluever, id=42, pet=null}"
这个特性,很适合做数据清洗,要比apache的validator方便;validator可以是一个事件驱动方式工作,而guava更像是annotation方式工作。
2. String JOIN,Split
Joiner concatenates strings using a delimiter
● throws a NPE on null objects, unless:
○ .skipNulls()
○ .useForNull(String)
private static final Joiner JOINER =
Joiner.on(", ").skipNulls();
JOINER.join("Kurt", "Kevin", null, "Chris");
// yields: "Kurt, Kevin, Chris"
这join 不如apache的collections和apache的commons-lang库,apache的join和split更强大。唯一区别是,apache仍然是原有的JAVA风格;而这个像脚本风格,或者注释风格。
- Functional Programming
Function<F, T>
○ one way transformation of F into T
○ T apply(F input)
○ most common use: transforming collections (view)
Predicate<T>
○ determines true or false for a given T
○ boolean apply(T input)
○ most common use: filtering collections (view)
这个也与apache common中的factory库相似
private static final Predicate<Client> ACTIVE_CLIENT =
new Predicate<Client>() {
public boolean apply(Client client) {
return client.activeInLastMonth();
}
};
// Returns an immutable list of the names of
// the first 10 active clients in the database.
FluentIterable.from(database.getClientList())
.filter(ACTIVE_CLIENT)
.transform(Functions.toStringFunction())
.limit(10)
.toList();
FluentIterable API
● Chaining (returns FluentIterable)
○ skip
○ limit
○ cycle
○ filter, transform
● Querying (returns boolean)
○ allMatch, anyMatch
○ contains, isEmpty
● Converting
○ to{List, Set, SortedSet}
○ toArray
● Extracting
○ first, last, firstMatch (returns
Optional<E>)
○ get (returns E)
- TABLE
这个不错
Table<R, C, V>
A "two-tier" map, or a map with two keys (called the "row key"
and "column key").
● can be sparse or dense
○ HashBasedTable: uses hash maps (sparse)
○ TreeBasedTable: uses tree maps (sparse)
○ ArrayTable: uses V[][] (dense)
● many views on the underlying data are possible
○ row or column map (of maps)
○ row or column key set
○ set of all cells (as <R, C, V> entries)
● use instead of Map<R, Map<C, V>>