通过在 lambda 中包含某个字符来对数组中的字符串进行排序——使用包含?

sorting strings in an array by including a certain character with lambda -- using contains?

我正在努力创建一种对数组中的字符串进行排序的方法,方法是将所有包含“e”的单词放在前面(按照它们彼此之间的原始顺序)。我无法确定执行此操作的方法。它似乎不允许“.contains()”,我不明白这是为什么。如果有人能告诉我,我将不胜感激。

这是我的代码,其中 IDE 告诉我“包含”的使用未解决。

   /**
     * Sorts an array of Strings so that words that contain the letter 'e'
     * appear before all the other words.
     *
     * @param words the array of strings to be sorted.
     * @return a sorted array of Strings.
     */
    public String[] sortByLetterE(String[] words) {

       //create new String[]
       String [] eFirst = new String[words.length]; 
       
       //collect strings that include E/e
       eFirst.add(words.forEach(word -> {
           word.contains('E') || word.contains('e'); 
       }));

       //collect the remainders
       eFirst.add(words.forEach(word -> {
           !word.contains('E') && !word.contains('e'); 
       }));

       //return sorted array
       return eFirst; 
    }

我也不完全清楚如何以这种方式对数组进行排序。我在“排序”搜索中发现的所有内容都是人们给出明显的 .compareTo 来排序 alphabetically/numerically,这在这里没有帮助。

您可以将 Arrays.sort() 与自定义比较器一起使用。 Arrays.sort() 是稳定的,因此,它将保留相等元素的顺序。这是示例代码:

import java.util.Arrays;
import java.util.Comparator;

public class test {
    public static void main(String[] args){
        String[] words = {"cat", "eel", "dog", "elephant"};
        Arrays.sort(words, Comparator.comparingInt(a -> (a.contains("E") || a.contains("e") ? 0 : 1)));
        for(String word : words)
            System.out.println(word);
    }
}

输出:

eel
elephant
cat
dog

不确定排序是转到此处的正确方法。对于长列表,它可能有点矫枉过正(当然,这也可能)。

以下根据是否包含 'e' 对单词进行分组。单词在遇到时被映射,因此它们的相对顺序保持不变。然后将两个列表相互连接以获得最终结果。

String[] sorted = Arrays.stream(words)
        .collect(Collectors.groupingBy
                w -> w.toLowerCase().contains("e") ? 0 : 1))
        .values().stream().flatMap(List::stream)
        .toArray(String[]::new);

for (String s: sorted) {
  System.out.println(s);
}

版画

eel
elephant
cat
dog