标签:foreach print color jdk util cto 传统 style function
package test;
import lombok.extern.slf4j.Slf4j;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
/**
* Created by zyq on 2020/7/6.
*/
@Slf4j
public class BaseLambda {
public static void testForeach(){
//定义一个数组
String[] array={"AA","BB","CC","DD","EE","FF"};
//将数组转换成集合
List<String> list = Arrays.asList(array);
//传统的遍历方式
log.info("========传统的遍历方式:");
for(String obj :list){
log.info("========传统的遍历方式:"+obj);
}
// 使用 Lambda 表达式以及函数操作(functional operation)
log.info("============使用 Lambda 表达式以及函数操作(functional
operation)");
list.forEach((obj)->log.info(obj));
log.info("============使用双冒号操作符");
list.forEach(log::info);
list.forEach(System.out::println);
}
/**
* Stream 去重复
* String 和 Integer 可以使用该方法去重
*/
public static void testStreamDuplicates(){
//定义一个数组
String[] array={"AA","BB","CC","DD","EE","FF","AA","BB","CC","DD","EE","FF"};
// 转换成集合
List<String> list = Arrays.asList(array);
//Stream去重复
List<String> collect =
list.stream().distinct().collect(Collectors.toList());
collect.forEach(log::info);
}
public static void main(String[] args) {
testForeach();
//testStreamDuplicates();
}
}
运行testForeach()方法:
11:35:32.611 [main] INFO test.BaseLambda - ========传统的遍历方式: 11:35:32.615 [main] INFO test.BaseLambda - ========传统的遍历方式:AA 11:35:32.615 [main] INFO test.BaseLambda - ========传统的遍历方式:BB 11:35:32.615 [main] INFO test.BaseLambda - ========传统的遍历方式:DD 11:35:32.615 [main] INFO test.BaseLambda - ========传统的遍历方式:CC 11:35:32.615 [main] INFO test.BaseLambda - ========传统的遍历方式:EE 11:35:32.615 [main] INFO test.BaseLambda - ========传统的遍历方式:FF 11:35:32.615 [main] INFO test.BaseLambda - ============使用 Lambda 表达式以及函数操作(functional operation) 11:35:32.649 [main] INFO test.BaseLambda - AA 11:35:32.650 [main] INFO test.BaseLambda - BB 11:35:32.650 [main] INFO test.BaseLambda - DD 11:35:32.650 [main] INFO test.BaseLambda - CC 11:35:32.650 [main] INFO test.BaseLambda - EE 11:35:32.650 [main] INFO test.BaseLambda - FF 11:35:32.650 [main] INFO test.BaseLambda - ============使用双冒号操作符 11:35:32.651 [main] INFO test.BaseLambda - AA 11:35:32.651 [main] INFO test.BaseLambda - BB 11:35:32.651 [main] INFO test.BaseLambda - DD 11:35:32.651 [main] INFO test.BaseLambda - CC 11:35:32.651 [main] INFO test.BaseLambda - EE 11:35:32.651 [main] INFO test.BaseLambda - FF AA BB DD CC EE FF Process finished with exit code 0
运行testStreamDuplicates()方法:
11:45:42.314 [main] INFO test.BaseLambda - AA 11:45:42.317 [main] INFO test.BaseLambda - BB 11:45:42.318 [main] INFO test.BaseLambda - CC 11:45:42.318 [main] INFO test.BaseLambda - DD 11:45:42.318 [main] INFO test.BaseLambda - EE 11:45:42.318 [main] INFO test.BaseLambda - FF Process finished with exit code 0
注意:String[] array={"AA","BB","DD","CC","EE","FF"};是不会进行排序的。
标签:foreach print color jdk util cto 传统 style function
原文地址:https://www.cnblogs.com/dongyaotou/p/13254035.html