避免使用循环来操作List
2009-08-20 09:18
183 查看
Learning from functional languages, looping isn’t the best way to work on collections. Suppose we want to filter a list of persons to those who can drink beer. The loop versions looks like:
This can - even in Java - be rewritten to a more a functional programming style. For example using Google collections filter:
As remarked by Dave Jarvis, I should have dropped the getter, and he’s right ;-)
which would lead to better code down the road:
The predicate version is slightly larger, but consists of two parts. Each one is easier to understand. While the loop version gets unreadable fast with new requirements, the functional version can easily be combined,
List<Person> beerDrinkers = new ArrayList<Person>(); for (Person p: persons) { if (p.getAge() > 16) { beerDrinkers.add(p); } }
This can - even in Java - be rewritten to a more a functional programming style. For example using Google collections filter:
Predicate<HasAge> canDrinkBeer = new Predicate<HasAge>() { public boolean apply(HasAge hasAge) { return hasAge.getAge() > 16; } }; List<Person> beerDrinkers = filter(persons, canDrinkBeer);
As remarked by Dave Jarvis, I should have dropped the getter, and he’s right ;-)
Predicate canDrinkBeer = new Predicate() { public boolean apply(HasAge hasAge) { return hasAge.isOlderThan( 16 ); } };
which would lead to better code down the road:
Predicate canDrinkBeer = new Predicate() { public boolean apply( HasAge hasAge, HasAge otherAge ) { return hasAge.isOlderThan( otherAge ); } }
The predicate version is slightly larger, but consists of two parts. Each one is easier to understand. While the loop version gets unreadable fast with new requirements, the functional version can easily be combined,
List beerDrinkers = filter(filter(persons, canDrinkBeer), isMale);
相关文章推荐
- 使用线程安全的 MSWeakTimer ,它不会对目标进行retain操作,避免循环引用
- 使用线程安全的 MSWeakTimer ,它不会对目标进行retain操作,避免循环引用
- fragment、ListFragment使用ListView及自定义Listview等初始化操作
- PHP使用pdo连接access数据库并循环显示数据操作示例
- java使用jeids实现redis2.6的list操作(1)
- python list循环remove操作的神奇问题 推荐
- List循环使用remove()方法
- 使用RedisTemplate对list的操作
- 对C++ STL,list元素的循环删除操作
- hive:数据库“行专列”操作---使用collect_set/collect_list/collect_all & row_number()over(partition by 分组字段 [order by 排序字段])
- 提倡使用foreach语句来进行循环操作
- 对比ArrayList和LinkedList 使用普通循环和迭代循环的性能
- 使用STL中的list容器实现单链表的操作
- 在Python中操作列表之list.extend()方法的使用
- python 使用循环生成list
- java使用lambda表达式对List集合进行操作(JDK1.8)
- 不使用遍历循环、Linq与Lamba表达式快速对List集合进行筛选与排序——在集合类里使用Find、FindAll与Sort
- 使用单向循环链表实现字典操作 INSERT、DELETE 和 SEARCH
- Java基础---使用循环操作Java中的数组(三十一)
- 使用block时如何避免循环引用