例如目前有list<String> words = [a,an,eat,food,believe],找出list中所有长度大于3的单词数量毫无疑问是将list遍历比较后输出结果。
1.传统方式
最经典的版本是:
int count = 0;
for (int i = 0 ; i < words.length() ; i++)
{if ( words[i].length() > 3 ) count ++;}
System.out.println(count);
2.简洁方式
在J2SE 1.5 后,Java提供另一种更为简洁方式的循环:
int count = 0;
for (String w : words)
{if ( w.length() > 3 ) count ++;}
System.out.println(count);
3.流方式
Java 8 中引入了流库,所以可以通过流的方式来进行遍历:
int count = words.stream().filter(w -> w.length() >3).count();
System.out.println(count);
4.并行流方式
仅需将stream改为parallelStream就可以使用并行流方式:
int count = words.parallelStream().filter(w -> w.length() >3).count();
System.out.println(count);