Do not use loops for list operations 본문

Programming/Java

Do not use loops for list operations

halatha 2011. 4. 27. 05:36
//	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.getAge() > 16 )	{
				beerDrinkers.add(p);
			}
		}

		Predicate<HasAge>	canDrinkBeer	=	new Predicate<HasAge>(){
			public boolean apply(HasAge hasAge)	{
				return	hasAge.getAge() > 16;
			}
		};
		Iterable<Person>	beerDrinkers2	=
			Iterables.filter(persons, canDrinkBeer);
		UnmodifiableIterator<Person>	beerDrinkers3	=
			Iterators.filter(persons.listIterator(), canDrinkBeer);
	}
}

interface HasAge	{
	public int getAge();
}

class Person implements HasAge	{
	final String	name;
	final int	age;

	public Person(String name, int age)
	{
		this.name	=	name;
		this.age	=	age;
	}

	public String getName()	{	return	this.name;	}
	public int getAge()		{	return	this.age;	}
	public String toString(){	return	name + " = " + age;	}
}
Comments