java arraylist排序和优化

java arraylist排序和优化,java,Java,我在下面编写了一个构造函数,它从文件中提取一个单词,将其传递给一个外部方法“Translate”,该方法返回单词的翻译 并行地(对于我还没有完全编写的代码),构造函数将字符串作为一个单词,它将(一旦编写代码)在字典中查找该单词 但在我这么做之前,我需要把单词和翻译都放在ArrayList中。我知道地图会更好,但我需要使用ArrayList 我的代码可以做到这一点,但有一些东西我不明白 我将单词写入数组列表,然后是翻译…所以我希望数组列表是Word1,Translation1,Word2,Tran

我在下面编写了一个构造函数,它从文件中提取一个单词,将其传递给一个外部方法“Translate”,该方法返回单词的翻译

并行地(对于我还没有完全编写的代码),构造函数将字符串作为一个单词,它将(一旦编写代码)在字典中查找该单词

但在我这么做之前,我需要把单词和翻译都放在ArrayList中。我知道地图会更好,但我需要使用ArrayList

我的代码可以做到这一点,但有一些东西我不明白

我将单词写入数组列表,然后是翻译…所以我希望数组列表是Word1,Translation1,Word2,Translation2

但当我运行print命令时,它会打印所有的单词,然后打印所有的翻译

我之所以想弄明白这一点,是因为我希望能够对单词上的数组列表进行排序(字典未排序),然后查找单个单词……并快速获取其翻译

所以我的问题是-我是否正确使用了ArrayList(在本练习中接受ArrayList的限制,如何使用word作为键进行排序

import java.io.FileNotFoundException;
导入java.nio.file.Path;
导入java.nio.file.path;
导入java.util.ArrayList;
导入java.util.Scanner;
课堂翻译{
字符串原件;
字符串翻译;
公共翻译(字符串原始)引发FileNotFoundException{
this.original=原件;
这个。翻译=翻译;
ArrayList al=新的ArrayList();
Path p1=Path.get(“C:/Users/Green/documents/dictionary.txt”);
Scanner sc=新的扫描仪(p1.toFile())。使用分隔符(“\\s*-\\s*”);
while(sc.hasNext()){
字符串字=(sc.next());
字符串翻译=(翻译(单词));
加(字);
增补(翻译);
System.out.println(“使用for循环的打印数组列表”);
对于(int i=0;i
使用Java 7按字母顺序排列字符串(经典方式): 使用Comparator Java 8:
查找word Java 7: 使用包含: 查找word Java 8:
List matches=List.stream()
.filter(it->it.contains(“txt”))
.collect(Collectors.toList());

HashSet
vs
ArrayList
中执行
contains()
  • contains()
    方法
    HashSet
    中比
    ArrayList

参考:

为什么不尝试联系字符串和翻译并将它们存储在同一索引中?您应该将单词和翻译组合在一个条目中。可以是一个带有两个字段的自定义类,也可以是一对,甚至是一个
字符串[2]
。否则你必须非常小心,不要弄乱顺序。谢谢你,但是如果我有两个数组列表项:al.add(word);al.add(translation);没有两个数组列表项,只有一个:
al.add(新字符串[]{word,translation});
al.add(成对的(word,translation))
al.add(新单词加翻译(单词,翻译));
for (int i = 0; i < count; i++) {
    for (int j = i + 1; j < count; j++) { 
        if (str[i].compareTo(str[j])>0) {
            temp = str[i];
            str[i] = str[j];
            str[j] = temp;
        }
    }
}
arrayList.sort((p1, p2) -> p1.compareTo(p2));
arrayList.sort(Comparator.comparing(MyObject::getA));
List <String> listClone = new ArrayList<String>(); 
for (String string : list) {
    if(string.matches("(?i)(text).*")) {
        listClone.add(string);
    }
}
Set<String> set = new HashSet<String>(list);
if (set.contains("text")) {
    System.out.println("String found!");
}
for (String s : list) {
    if (s.contains("text")) {
        System.out.println(s);
    }
}
List<String> matches = list.stream()
                           .filter(it -> it.contains("txt")) 
                           .collect(Collectors.toList());