## Guava 教程3-Java 的函数式编程，通过 Google Collections 过滤和调用已翻译 100%

se77en 投递于 2013/01/29 17:06 (共 7 段, 翻译完成于 02-18)

#### 参与翻译 (2人) : JoeyBlue, mikezhaotb

Functions, Functions, Functions!!

mikezhaotb

```topMap = Maps.transformValues(fromMap, function);
toList = Lists.transform(fromList, function);```

```Map usdPriceMap = Maps.transformValues(eurPriceMap, new Function() {
double eurToUsd = 1.4888;
public Double apply(final Double from) {
return from * eurToUsd;
}
});```

JoeyBlue

`List<String> names = listOf("Aleksander", "Jaran", "Integrasco", "Guava", "Java");`

JoeyBlue

`Iterable<String> filtered = filter(names, or(or(equalTo("Aleksander"),equalTo("Jaran")), lengthLessThan(5)));`

```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;
}
}```

```public static Predicate<String> lengthLessThan(final int length) {
return new LengthLessThanPredicate(length);
}```

JoeyBlue

`Collections.sort(List<T>, Comparator<? super T>)`

```Comparator<Person> byLastName = new Comparator<Person>() {
public int compare(final Person p1, final Person p2) {
return p1.getLastName().compareTo(p2.getLastName());
}
}```
```Comparator<Person> byFirstName = new Comparator<Person>() {
public int compare(final Person p1, final Person p2) {
return p1.getFirstName().compareTo(p2.getFirstName());
}
};
```

`List<Person> sortedCopy = Ordering.from(byLastName).compound(byFirstName).reverse().sortedCopy(persons);`

`List<Person> sortedCopy = orderByLastName.compound(orderByFirstName).reverse().sortedCopy(persons);`
JoeyBlue

### 继续过滤和排序

`people.filter(_.firstName == "Steve").sort(_.lastName < _.lastName) `

`Ordering.from(byLastName).sortedCopy(filter(persons, withFirstName("Steve")));`

JoeyBlue

JoeyBlue

### 评论(23)

E

E

#### 引用来自“Ellipse”的评论

common-lang之类的是没有问题的，但是把代码写成函数式风格，在代码评审的时候会被喷的

E

#### 引用来自“Ellipse”的评论

common-lang之类的是没有问题的，但是把代码写成函数式风格，在代码评审的时候会被喷的