Joiner
Guava中Joiner的用法:
int [] numbers
= {
1 ,
2 ,
3 ,
4 ,
5 };
String numbersAsString
= Joiner.on(
";" ).join(
Ints.asList(numbers));
另一种写法:
String numbersAsStringDirectly
= Ints.join(
";" , numbers);
Joiner的用法:
以前这样写:
public
class ShoppingList {
private List
<Item
> items
= ...;
...
public String toString() {
StringBuilder stringBuilder
=
new StringBuilder();
for (Iterator
<Item
> s
= items.iterator(); s.hasNext(); ) {
stringBuilder.append(s.next());
if (s.hasNext()) {
stringBuilder.append(
" and " );
}
}
return stringBuilder.toString();
}
}
现在这样写:
public
class ShoppingList {
private List
<Item
> items
= ...;
...
public String toString() {
return
Join.join(
" and " , items);
}
}
Splitter
Guava中Splitter的用法:
Iterable split
= Splitter.on(
"," ).split(numbsAsString);
对于这样的字符串进行切分:
String testString
=
"foo , what,,,more," ;
Iterable
<String
> split
= Splitter.on(
"," ).omitEmptyStrings().trimResults().split(testString);
Preconditions:验证与条件检查
原来的写法:
if (count
<
=
0 ) {
throw
new IllegalArgumentException(
"must be positive: "
+ count);
}
Guava的写法(Jakarta Commons中有类似的方法):
Preconditions.checkArgument(count
>
0 ,
"must be positive: %s" , count);
一个更酷的用法:
public PostExample(
final String title,
final Date date,
final String author) {
this .title
=
Preconditions.checkNotNull(title);
this .date
= checkNotNull(date);
this .author
= checkNotNull(author);
}
Objects
public
boolean equals(Object o) {
if (o
instanceof Order) {
Order that
= (Order)o;
return
Objects.equal(address, that.address)
&& Objects.equal(targetArrivalDate, that.targetArrivalDate)
&& Objects.equal(lineItems, that.lineItems);
}
else {
return false ;
}
}
public static boolean equal(Object a, Object b)
{
return a == b || a != null && a.equals(b);
}
public
int hashCode() {
return
Objects.hashCode(address, targetArrivalDate, lineItems);
}
public static transient int hashCode(Object objects[])
{
return Arrays.hashCode(objects);
}
import com.google.common.base.Objects;
public
class Point {
public Integer x;
public Integer y;
public Point(Integer x, Integer y) {
this.x
= x;
this.y
= y;
}
@Override
public String toString() {
// 等同于 String.format("Point{x=%d, y=%d}", x, y);
return
Objects.toStringHelper(
this)
.add(
"x", x)
.add(
"y", y)
.toString();
}
@Override
public
boolean equals(Object that) {
if(that
instanceof Point) {
Point p
= (Point) that;
return
Objects.equal(x, p.x)
&& Objects.equal(y, p.y);
}
return false;
}
@Override
public
int hashCode() {
return
Objects.hashCode(x, y);
}
Strings
关于Strings的一些用法( http://blog.ralscha.ch/?p=888):
assertEquals(
"test" ,
Strings.emptyToNull(
"test" ));
assertEquals(
" " , Strings.emptyToNull(
" " ));
assertNull(Strings.emptyToNull(
"" ));
assertNull(Strings.emptyToNull( null ));
assertFalse(
Strings.isNullOrEmpty(
"test" ));
assertFalse(Strings.isNullOrEmpty(
" " ));
assertTrue(Strings.isNullOrEmpty(
"" ));
assertTrue(Strings.isNullOrEmpty( null ));
assertEquals(
"test" ,
Strings.nullToEmpty(
"test" ));
assertEquals(
" " , Strings.nullToEmpty(
" " ));
assertEquals(
"" , Strings.nullToEmpty(
"" ));
assertEquals(
"" , Strings.nullToEmpty( null ));
assertEquals(
"Ralph_____" ,
Strings.padEnd(
"Ralph" ,
10 ,
'_' ));
assertEquals(
"Bob_______" , Strings.padEnd(
"Bob" ,
10 ,
'_' ));
assertEquals(
"_____Ralph" ,
Strings.padStart(
"Ralph" ,
10 ,
'_' ));
assertEquals(
"_______Bob" , Strings.padStart(
"Bob" ,
10 ,
'_' ));
assertEquals(
"xyxyxyxyxy" ,
Strings.repeat(
"xy" ,
5 ));
Throwables
(将检查异常转换成未检查异常):
Before:
public
void doSomething()
throws IOException, SQLException {
try {
someMethodThatCouldThrowAnything();
}
catch (IKnowWhatToDoWithThisException e) {
handle(e);
}
catch (SQLException e) {
log(e);
throw e;
}
catch (IOException e) {
log(e);
throw e;
}
catch (Throwable t) {
log(t);
throw
new RuntimeException(t);
}
}
After:
public
void doSomething()
throws IOException, SQLException {
try {
someMethodThatCouldThrowAnything();
}
catch (IKnowWhatToDoWithThisException e) {
handle(e);
}
catch (Throwable t) {
log(t);
Throwables.propagateIfInstanceOf(t, IOException.
class );
Throwables.propagateIfInstanceOf(t, SQLException.
class );
throw
Throwables.propagate(t);
}
}
Functions用于转换集合
(闭包功能)
Function
<String, Integer
> strlen
=
new Function
<String, Integer
>() {
public Integer
apply(String from) {
Preconditions.checkNotNull(from);
return from.length();
}
};
List
<String
> from
= Lists.newArrayList(
"abc" ,
"defg" ,
"hijkl" );
List
<Integer
> to
=
Lists.transform(from, strlen);
for (
int i
=
0 ; i
< from.size(); i
++) {
System.out.printf(
"%s has length %d\n" , from.get(i), to.get(i));
}
不过这种转换是在访问元素的时候才进行, 下面的例子可以说明:
Function
<String, Boolean
> isPalindrome
=
new Function
<String, Boolean
>() {
public Boolean
apply(String from) {
Preconditions.checkNotNull(from);
return
new StringBuilder(from).reverse().toString().equals(from);
}
};
List
<String
> from
= Lists.newArrayList(
"rotor" ,
"radar" ,
"hannah" ,
"level" ,
"botox" );
List
<Boolean
> to
= Lists.
transform(from, isPalindrome);
for (
int i
=
0 ; i
< from.size(); i
++) {
System.out.printf(
"%s is%sa palindrome\n" , from.get(i), to.get(i)
?
" "
:
" NOT " );
}
// changes in the "from" list are reflected in the "to" list
System.out.printf(
"\nnow replace hannah with megan...\n\n" );
from.set( 2 , "megan" );
for (
int i
=
0 ; i
< from.size(); i
++) {
System.out.printf(
"%s is%sa palindrome\n" , from.get(i), to.get(i)
?
" "
:
" NOT " );
}
rotor is a palindrome
radar is a palindrome
hannah is a palindrome
level is a palindrome
botox is NOT a palindrome
now replace hannah with megan...
rotor is a palindrome
radar is a palindrome
megan is NOT a palindrome
level is a palindrome
botox is NOT a palindrome
Predicate用于过滤
public interface Predicate
{
public abstract boolean apply(Object obj);
public abstract boolean equals(Object obj);
}
com.google.common.collect.
Sets.filter(Set, Predicate)
private
static
class LengthLessThanPredicate
implements Predicate
<String
> {
private
final
int length;
private LengthLessThanPredicate(
final
int length) {
this.length
= length;
}
public
boolean
apply(
final String s) {
return s.length()
< length;
}
}
Set result
= Sets.filter(mySet,
new LengthLessThanPredicate(
5));
CharMatcher?
从字符串中得到、去掉所有数字:
assertEquals(
"89983" , CharMatcher.DIGIT.retainFrom(
"some text 89983 and more" ))
assertEquals(
"some text and more" , CharMatcher.DIGIT.removeFrom(
"some text 89983 and more" ))