Recent Posts
Recent Comments
Link
| 일 | 월 | 화 | 수 | 목 | 금 | 토 |
|---|---|---|---|---|---|---|
| 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 | 28 | 29 |
| 30 |
Tags
- Software Engineering
- management
- Artificial Intelligence
- history
- essay
- QT
- Italy
- Malaysia
- AI
- Book
- Kuala Lumpur
- ubuntu
- web
- MySQL
- Programming
- django
- France
- hbase
- comic agile
- erlang
- leadership
- agile
- Linux
- programming_book
- Java
- program
- Python
- RFID
- hadoop
- Book review
Archives
- Today
- Total
Do not use loops for list operations 본문
2011/04/26 - [Programming/Java] - Do not use loops for list operations
// item 3 from http://codemonkeyism.com/generation-java-programming-style
// http://code.google.com/p/google-collections
// http://blogs.warwick.ac.uk/chrismay/entry/writing_functional_java
// http://codemunchies.com/2009/11/functional-java-filtering-and-ordering-with-google-collections-part-3
// http://stackoverflow.com/questions/2312849/filter-and-sort-list-using-google-collections
import java.util.ArrayList;
import java.util.List;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.collect.UnmodifiableIterator;
import com.google.common.collect.Lists;
public class TestFilter {
public static void main(final String[] args) {
List<Person> persons = Lists.newArrayList(
new Person("A", 15),
new Person("B", 16),
new Person("C", 17));
List<Person> beerDrinkers = new ArrayList<Person>();
for ( Person p : persons ) {
if ( p.isOlderThan(16) ) {
beerDrinkers.add(p);
}
}
System.out.println(beerDrinkers);
Predicate<HasAge> canDrinkBeer = new Predicate<HasAge>(){
public boolean apply(HasAge hasAge) {
return hasAge.isOlderThan(16);
}
};
Iterable<Person> beerDrinkers2 =
Iterables.filter(persons, canDrinkBeer);
System.out.println(beerDrinkers2);
UnmodifiableIterator<Person> beerDrinkers3 =
Iterators.filter(persons.listIterator(), canDrinkBeer);
System.out.println(beerDrinkers3.next());
}
}
interface HasAge {
public boolean isOlderThan(int age);
}
class Person implements HasAge {
public final String name;
public final int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public boolean isOlderThan(int age) { return age < this.age; }
public String toString(){ return name + " = " + age; }
}
Comments