1、 使用IntStream实现的几种方法
intStream文档:https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
1) IntStream.range
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
System.out.println(getIndexList("Hello world!",'l'));
System.exit(0); //success
}
public static List<Integer> getIndexList(String s, char c) {
return IntStream.range(0, s.length())
.filter(index -> s.charAt(index) == c)
.boxed()
.collect(Collectors.toList());
}
}
2) IntStream.iterate
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
System.out.println(getIndexList("Hello world!",'l'));
System.exit(0); //success
}
public static List<Integer> getIndexList(String s, char c) {
return IntStream.iterate(s.indexOf(c), i -> s.indexOf(c, i + 1))
.takeWhile(i -> i > -1)
.boxed()
.collect(Collectors.toList());
}
}
或
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
System.out.println(getIndexList("Hello world!",'l'));
System.exit(0); //success
}
private static List<Integer> getIndexList(String word, char c) {
return IntStream
.iterate(word.indexOf(c), index -> index >= 0, index -> word.indexOf(c, index + 1))
.boxed()
.collect(Collectors.toList());
}
}
2、使用Stream.of实现
import java.util.Scanner;
import java.util.regex.MatchResult;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
Stream.of("Hello world!")
.map(Scanner::new) // 将字符串映射为 Scanner 对象
.flatMap(s -> s.findAll("l")) // 查找所有匹配字符 "l" 的位置
.map(MatchResult::start) // 获取匹配结果的开始位置
.forEach(System.out::println); // 打印每个位置索引
System.exit(0); //success
}
}