java学习脚印:几种迭代方式

java学习脚印:几种迭代方式



     java语言提供了多种迭代方式,但不是每一种都能完成你想要的功能,下面是来自官网的一道题目:


      Write a method that takes a List<String> and applies String.trim to each element. To do this, you'll need to pick one of the three iteration idioms that you described in Question 1. Two of these will not give the result you want, so be sure to write a program that demonstrates that the method actually works!


    简而言之,就是实现在迭代一个列表过程中使用String.trim函数来去除元素的头部和尾部的空格。

下面给出这个题目的实现方式,注意体会几种迭代方式的限制。


package com.learningjava;

import java.util.*;
/**
 * this program try more ways to traverse a List
 * @author wangdq
 * 2013-11-2
 */
public class CollectionsDemo6 {
	public static void main(String[] args) {
		String[] ads = new String[]{" what ", " you ", " see ", " is ",
				" what " ," you "," get "};
		List<String>  list= Arrays.asList(ads);
		System.out.println("before: "+list);
		TrimList_version1(list);//change version to observe result
		System.out.println("after:  "+list);
	}
	//version1 work ,but not encouraged
	public static void TrimList_version1 (List<String> list) {
		for(int i = 0 ;i<list.size();i++)
			list.set(i, list.get(i).trim());
	}
	//version2 not work
	//Limitations: cannot be used to add, remove, or modify elements.
	public static void TrimList_version2 (List<String> list) {
		for(String s:list) {
			// change to the temporary variable
			// will not affect the value in the container
			s = s.trim();
		}
	}
	//version3 not work
	//Limitations: cannot be used to modify elements.
	public static void TrimList_version3 (List<String> list) {
		for(Iterator<String> it = list.iterator();it.hasNext();) {
			it.next().trim();
		}
	}
	//version4 work
	//Limitations: none.
	public static void TrimList_version4 (List<String> list) {
		for(ListIterator<String> listIt = list.listIterator();listIt.hasNext();) {
			listIt.set(listIt.next().trim());
		}
	}
	//version5  JDK 8  Lambda Expressions 
	/* almost like the following:
	 * 
	public static void TrimList_version5 (List<String> list) {
		list
		.stream()
		.forEach(e -> e.set(e.trim());
	}
	*/
}

version1版本运行结果

before: [ what ,  you ,  see ,  is ,  what ,  you ,  get ]
after:  [what, you, see, is, what, you, get]


其他几个版本的运行结果,你可以通过切换版本来执行查看,

注意体会几种迭代方式的差别和限制。


你可能感兴趣的:(java学习脚印:几种迭代方式)