Search code examples
javalambdacontains

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


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.


Solution

  • 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