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]


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

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值