Search code examples
javacollectionssubsetsortedset

How to subSet from SortedSet<String>


I have to write a code that makes it possible to delete all the words of a SortedSet starts with K.

import java.util.*;

public class Deleter {
    
    public static void deleteKWords(SortedSet<String> set) {
        set.subSet("K", "");
}
    }
    
}

I've heard that with a subSet can simple solved but i couldn't.


Solution

  • You can achive what you want by using Java 8 stream:

    public static SortedSet<String> deleteKWords(SortedSet<String> set) {
       return new TreeSet<>(set
               .stream()
               .filter((s) -> !s.startsWith("K"))
               .collect(Collectors.toSet()));
    
    }
    

    Edit: Probably it will be more efficient to avoid creating new object every time and just modify the one you send to the method:

     public static SortedSet<String> deleteKWords(SortedSet<String> set) {
        set.removeAll(set
                .stream()
                .filter((s) -> s.startsWith("K"))
                .collect(Collectors.toList()));
        return set;
    
    }