-1

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.

merdle
  • 264
  • 2
  • 20
  • 1
    Read the javadoc of [`subSet()`](https://docs.oracle.com/javase/8/docs/api/java/util/SortedSet.html#subSet-E-E-) and [`clear()`](https://docs.oracle.com/javase/8/docs/api/java/util/Set.html#clear--), then combine them: `set.subSet("K", "L").clear()` – Andreas Jan 17 '17 at 20:08
  • 1
    http://stackoverflow.com/questions/1110404/remove-elements-from-a-hashset-while-iterating – Tomas F. Jan 17 '17 at 20:08
  • I'm voting to close this question as off-topic because [questions asking for homework help must include a summary of the work done so far to solve the problem, and a description of the difficulty solving it](http://stackoverflow.com/help/on-topic). – Andreas Jan 17 '17 at 20:09

2 Answers2

2

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;

}
1

You can simply do this by combining subSet() and removeAll() methods:

public static void deleteKWords(SortedSet<String> set) {
    Set s = new TreeSet<>(set.subSet("K", "O"));
    set.removeAll(s);
}
Michał Szewczyk
  • 5,656
  • 7
  • 28
  • 41