「掘金者说」如何使用forEach提供index值

831 阅读1分钟

掘金者说,基于该工具方法,便可轻松编写如下业务代码,清晰、简洁、优雅。业务需求:通过遍历,同时使用使用的index,那么如何获取到呢?如何去拿到?查找了点资料,进行单元测试,验证过笔记。

案例

  • 单元测试1:实现,待优化
	/**
	 * Java8遍历集合  show me the code
	 */
	@Test
	void testJava8TcIndex1() {
		List<String> list = Arrays.asList("show", "me", "the", "code");
		for (int index = 0; index < list.size(); index++) {
			String item = list.get(index);
			System.out.println("listItem [" + index + "] = " + item);
		}
	}
  • 结果:满足需求,可以实现。但是,未使用到forEach
listItem [0] = show
listItem [1] = me
listItem [2] = the
listItem [3] = code

优化

  • 单元测试2:实现
	/**
	 * Java8遍历集合  show me the code
	 */
	@Test
	void testJava8TcIndex2() {
		List<String> list = Arrays.asList("show", "me", "the", "code");

		list.forEach(LambdaUtils.consumerWithIndex((item, index) -> {
			System.out.println("listItem [" + index + "]=" + item);
		}));
	}
  • 结果:满足需求,可以实现。且使用到forEach
listItem [0] = show
listItem [1] = me
listItem [2] = the
listItem [3] = code

工具类

/**
 * 基于该工具方法,便可轻松编写如下业务代码,清晰、简洁
 *
 * @description:Java8的forEach(...)如何提供index值
 * @author: Lucky
 * @create: 2020-08-13
 **/
public class LambdaUtils {
	/**
	 * 工具方法
	 * @param consumer
	 * @param <T>
	 * @return
	 */
	public static <T> Consumer<T> consumerWithIndex(BiConsumer<T, Integer> consumer) {
		class Obj {
			int i;
		}
		Obj obj = new Obj();
		return t -> {
			int index = obj.i++;
			consumer.accept(t, index);
		};
	}
}

参考资料

Java8的forEach(...)如何提供index值