在Java中,我有一个要与String语句匹配的String列表。无论适合什么,字符串都必须获得该索引的索引/(另外向索引中添加一些数字)。用Java 8实现这一点的最佳方法是什么?例如:
List tobeMatched = new ArrayList<>(Arrays.asList("History","Geography"));
String sentence1 = "Chapter History is a boring one";如果sentence1包含历史,则返回历史索引+7,即: 14,如果sentence1包含地理,则返回历史索引+9;
我想实现两件事:
sentence1包含History is true,还返回历史记录的索引+历史长度(匹配元素)= 14。
正常情况下,我可以这样做:
int index = 0;
for(String match : tobeMatched)
{
if(sentence1.contains(match ))
index = sentence1.indexOf(match)+match.length();
}
return index;我想做Java 8。
发布于 2021-12-06 05:20:22
我想
我想做Java 8。
意味着您想使用流。
使用流不会自动使代码更好。正如俗话说:正确的工具,正确的工作,在我看来,流不是正确的工具,你想做的工作。
尽管如此,下面的代码实现了您的目标,尽管不是通过流实现的,因为正如我已经说过的,流不适合您的任务,并且您当前的代码可能是最好的方法。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class Test {
private static int index;
public static void main(String[] args) {
List<String> tobeMatched = new ArrayList<>(Arrays.asList("History","Geography"));
String sentence1 = "Chapter History is a boring one";
OptionalInt result = IntStream.range(0, tobeMatched.size())
.filter(i -> {
index = sentence1.indexOf(tobeMatched.get(i));
return index >= 0;
})
.findFirst();
System.out.println(index + tobeMatched.get(result.getAsInt()).length());
}
}运行上面的代码打印15。
如果sentence1不包含来自tobeMatched的单词,那么上面代码的最后一行将抛出java.util.NoSuchElementException
正如您从上面的代码中看到的,在使用流时获得中间结果并不简单,因此我先前的声明认为流可能不是完成任务的最佳方式。
https://stackoverflow.com/questions/70240671
复制相似问题