Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 根据另一个字符串数组定义的顺序对字符串数组列表进行排序_Java_Sorting_Arraylist - Fatal编程技术网

Java 根据另一个字符串数组定义的顺序对字符串数组列表进行排序

Java 根据另一个字符串数组定义的顺序对字符串数组列表进行排序,java,sorting,arraylist,Java,Sorting,Arraylist,我见过其他几个类似的问题,但我还没有找到任何解决我问题的方法 根据ORDERarray对numberWordsArrayList进行排序的方法是什么 我并不是说numberWords必须是ArrayList,它也可以是array,但我认为它可能更适合getStoredWords()方法,因为我应该返回List。 试图将numberWords与ORDER进行比较,例如numberWords.get(first).equals(ORDER[first]),但结果不符合要求 public class

我见过其他几个类似的问题,但我还没有找到任何解决我问题的方法

根据
ORDER
array对
numberWords
ArrayList进行排序的方法是什么

我并不是说
numberWords
必须是
ArrayList
,它也可以是
array
,但我认为它可能更适合
getStoredWords()
方法,因为我应该返回
List
。 试图将
numberWords
ORDER
进行比较,例如
numberWords.get(first).equals(ORDER[first])
,但结果不符合要求

public class WordStore {
    List<String> numberWords = new ArrayList<>();

    private static final String[] ORDER = {
            "one", "two", "three", "four", "five",
            "six", "seven", "eight", "nine", "ten"
    };

    public void add(String numberAsWord) {
        numberWords.add(numberAsWord);
    }

    public List<String> getStoredWords() {
        
    }
}

它可以是一行程序,但不要这样做,这种方法在性能方面不是很好

numberWords.sort(Comparator.comparingInt(ORDER::indexOf));               // DON'T use me
但是,让我们重复使用基于每个单词索引的查找的思想作为顺序定义

您需要两个步骤:

  • 提取:为
    顺序中的每个单词指定数字顺序
    。数据结构
    Map
    适合它。
    HashMap
    对于基于单词的查找非常有用

    Map<String, Integer> orders = IntStream.range(0, ORDER.length)
            .boxed()
            .collect(Collectors.toMap(i -> ORDER[i], Function.identity()));
    

  • 它可以是一行程序,但不要这样做,这种方法在性能方面不是很好

    numberWords.sort(Comparator.comparingInt(ORDER::indexOf));               // DON'T use me
    
    但是,让我们重复使用基于每个单词索引的查找的思想作为顺序定义

    您需要两个步骤:

  • 提取:为
    顺序中的每个单词指定数字顺序
    。数据结构
    Map
    适合它。
    HashMap
    对于基于单词的查找非常有用

    Map<String, Integer> orders = IntStream.range(0, ORDER.length)
            .boxed()
            .collect(Collectors.toMap(i -> ORDER[i], Function.identity()));
    

  • 你需要像Lino已经建议的那样,按照
    顺序将单词映射到它们的位置。对于较大的列表,您也可以考虑使用<代码> map < /COD>,它将单词(键)映射到某个顺序(在这种情况下,这些值可以是实际整数值)。它不适用于
    binarySearch
    您需要像Lino已经建议的那样,将单词映射到它们在
    顺序中的位置。对于较大的列表,您也可以考虑使用<代码> map < /COD>,它将单词(键)映射到某个顺序(在这种情况下,这些值可以是实际的整数值)。
    
    numberWords.sort(Comparator.comparingInt(orders::get));