首先,我们一起看看stream的层次体系关系:
一般我们直接使用Strem,比如我们需要从一个指定的字符串数组中,查找指定的字符串是否存在
未使用stream的时候:
import org.junit.Test;
import java.util.*;
/**
- Created by liqi on 2021/7/29
*/
public class FindStringTest {
@Test
public void testFindStr() {
String findStr = “b”;
List stringList = Arrays.asList(“a”, “b”, “c”, “d”, “e”);
boolean match = false;
for (String data : stringList) {
if (data.equals(findStr)) {
match = true;
break;
}
}
System.out.println(match ? “存在” : “不存在”);
}
}
输出:
存在
使用steam:
@Test
public void testFindStrByStream() {
String findStr = “b”;
List stringList = Arrays.asList(“a”, “b”, “c”, “d”, “e”);
boolean result = stringList.stream().anyMatch(x -> x.equals(findStr));
System.out.println(result);
}
输出:
存在
stream的操作符主要分为中间操作符和终止操作符
中间操作:
1.filter
过滤数据,保留 boolean 为 true 的元素,返回一个集合 @Test
public void testFilterByStream() {
List integerList = Arrays.asList(10, 11, 53, 1, 57, 9);
System.out.println(integerList.stream().filter(x -> x > 30).collect(Collectors.toList()));
}
2.map(T -> R)
转换操作符,可以做数据转换,比如:把字符串转换成int、long、double,或者把一个实体转换成另外一个实体。包含:map,mapToInt、mapToLong、mapToDouble
@Test
public void testMapByStream() {
List integerList = Arrays.asList(10d, 11d, 53d, 1d, 57d, 9d);
integerList.stream().mapToInt(x->x.intValue()).forEach(System.out::println);
}
未完待续