// 创建一个顺序流 Stream<String> stream = list.stream();
// 创建一个并行流 Stream<String> parallelStream = list.parallelStream();
List<Integer> list = Arrays.asList(7, 6, 9, 3, 8, 2, 1);
// 遍历输出符合条件的元素
list.stream().filter(x -> x > 6).forEach(System.out::println);
// 匹配第一个
Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst();
// 匹配任意(适用于并行流)
Optional<Integer> findAny = list.parallelStream().filter(x -> x > 6).findAny();
// 是否包含符合特定条件的元素
boolean anyMatch = list.stream().anyMatch(x -> x > 6);
System.out.println("匹配第一个值:" + findFirst.get());
System.out.println("匹配任意一个值:" + findAny.get());
System.out.println("是否存在大于6的值:" + anyMatch);
过滤 filter
映射 map
List<Long> uniqueMons = list.stream()
.map(SubContractRelation::getSno)
.filter(mon -> !Arrays.asList(ids).contains(mon))
.collect(Collectors.toList());
List<String> fiterList = personList.stream().filter(x -> x.getSalary() > 8000).map(Person::getName)
.collect(Collectors.toList());
System.out.print("高于8000的员工姓名:" + fiterList);
map映射提取出sno字段,filter根据mon筛选,list的contains方法去重最后通过collect整合到list中去
进阶:使用stream流实现最长不重复子串
public static void main(String[] args) {
String input = "abcdedafg";
List<Character> charList = input.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.toList());
String longestSubstring = findLongestSubstring(charList);
System.out.println("最长不重复子串: " + longestSubstring);
}
public static String findLongestSubstring(List<Character> list) {
List<Character> longestSubstring = list.stream()
.distinct()
.collect(Collectors.toList());
String longestSubstringString = longestSubstring.stream()
.map(Object::toString)
.collect(Collectors.joining());
return longestSubstringString;
}
先获取stream流使用
input.chars()
:将字符串input
转换为一个 IntStream 流,其中每个元素都表示字符串中的一个字符对应的 ASCII 值。.mapToObj(c -> (char) c)
:对流中的每个 ASCII 值进行映射操作,将其转换为对应的字符。.collect(Collectors.toList())
:将字符流收集为一个列表,即将每个字符放入列表中。-
使用
distinct()
去除重复元素:使用distinct()
方法去除流中的重复元素,保留唯一的字符。 -
使用
collect()
方法将流收集为列表:使用collect(Collectors.toList())
方法将流中的字符收集为一个新的列表。 longestSubstring.stream()
:将longestSubstring
列表转换为一个字符流。.map(Object::toString)
:对流中的每个字符进行映射操作,将每个字符转换为字符串。.collect(Collectors.joining())
:将映射后的字符串元素收集起来,并使用空字符串连接它们,形成一个最终的字符串结果。
map
:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap
:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
组合 concat
跳过 skip
取前n个 limit