简体   繁体   English

如何从 SortedSet 子集<String>

[英]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.我必须编写一个代码来删除所有以 K 开头的 SortedSet 单词。

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.我听说使用 subSet 可以简单解决,但我不能。

You can achive what you want by using Java 8 stream:您可以使用 Java 8 流来实现您想要的:

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;

}

You can simply do this by combining subSet() and removeAll() methods:您可以通过组合 subSet() 和 removeAll() 方法来简单地做到这一点:

public static void deleteKWords(SortedSet<String> set) {
    Set s = new TreeSet<>(set.subSet("K", "O"));
    set.removeAll(s);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM