我想根据扫描仪输入是否与该索引中的任何单词匹配来返回 ArrayList 索引的内容。
因此,如果 ArrayList 索引 0 包含
<dog, cat, mouse>`
索引 1 包含
<football, baseball, rugby>
和scanner input = "football"
,
应打印完整的索引 1。
但是,我不确定如何做到这一点,所以任何建议都会很棒。
编辑:
下面的代码读取我从中获取数据的文件,并将每个单独的行存储为索引。
while (fileScanner.hasNextLine()) {
editList.add(fileScanner.nextLine());
}
下面的代码读取输入,如果在 editList 中找到 editScanner 输入,则应打印索引。但是,我知道这是不正确的,但我完全不确定如何将索引的内容打印为字符串
if (editList.contains(editScanner)) {
while (((edit = fileReader.readLine()) != null)) {
String chosenFilm = editList.indexOf(editScanner);
}
以这种方式将列表设置为集合的数组列表:
List<Set<String>> yourList = new ArrayList<>();
然后检查您是否必须打印索引,因为它上面有足球,只需做
yourList.get(i).contains("football")
如果无法在各种索引上重复足球,请改用 Map,使用足球作为键,索引足球作为值。然后,您可以检查索引并直接从列表中打印该索引。
考虑到您的结构是一个List<List<String>>
和input
:
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("dog", "cat", "mouse"));
list.add(Arrays.asList("football", "baseball", "rugby"));
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
您可以执行以下操作
遍历不同的
subLists
并找到好的(找到时停止(int index = -1; for (int i = 0; i < list.size(); i++) { // iterate if (list.get(i).contains(input)) { // check if present index = i; // keep index break; } }
使用
Streams
index = list.stream() // iterate .filter(l -> l.contains(input)) // keep sublist where present .mapToInt(list::indexOf) // transform it to its index .findFirst() // keep index .orElse(-1); // if not found return -1