使用Lambda将数组中包含特定字符的字符串进行排序 — 使用contains吗?

huangapple go评论40阅读模式
英文:

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

问题

我正在努力创建一个可以按照包含字母 "e" 的单词将字符串数组排序的方法(按照它们在原始顺序中相对于其他单词的顺序)。我在确定如何做到这一点方面遇到了问题。它似乎不允许使用 "contains()" 方法,我不明白为什么会这样。如果有人能告诉我,我会很感激。

这是我的代码,我的IDE告诉我 "contains" 方法未解析。

   /**
     * 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) {

       //创建新的 String[]
       String[] eFirst = new String[words.length]; 
       
       //收集包含 E/e 的字符串
       eFirst.add(words.forEach(word -> {
           word.contains('E') || word.contains('e'); 
       }));

       //收集其余部分
       eFirst.add(words.forEach(word -> {
           !word.contains('E') && !word.contains('e'); 
       }));

       //返回排序后的数组
       return eFirst; 
    }

我也不完全清楚如何以这种方式对数组进行排序。在我的 "排序" 搜索中,我只找到了人们提供明显的 ".compareTo" 方法来按字母/数字顺序排序的示例,这在这里没有帮助。

英文:

I'm working on creating a method that sorts strings in an array, by putting all words that contain "e" up front (in their original order relative to each other). I'm having trouble determining a way to do this. It doesn't seem to allow ".contains()", and I don't understand why this is. I'd appreciate if anyone could tell me.

Here's my code, in which my IDE tells me the use of "contains" is unresolved.

   /**
     * 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; 
    }

I'm also not totally clear on how to sort an array in such a manner. All I'm finding in my "sorting" searches is people giving the obvious .compareTo to sort things alphabetically/numerically, which doesnt help here.

答案1

得分: 2

你可以只使用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
英文:

You can just use Arrays.sort() with a custom comparator. Arrays.sort() is stable and as a result, it will preserve the order of equal elements. Here's example code:

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);
    }
}

Output:

eel
elephant
cat
dog

答案2

得分: 1

不确定在这里进行排序是否是正确的方法。对于长列表来说,这可能会有点过度(当然,这个方法也可能有点过度)。

以下是基于包含 "e" 或不包含 "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
英文:

Not certain that sorting is the proper way to go here. For long lists it could be overkill (of course, so could this).

The following groups the words based on containing an 'e' or not. The words are mapped as they are encountered so their relative order remains the same. The two lists are then concatenated to each other for the final result.

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);
}

Prints

eel
elephant
cat
dog


</details>



huangapple
  • 本文由 发表于 2020年7月28日 08:38:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/63125478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定