我必須找到只出現一次(不少于,不多于)的單詞并輸出它們。不幸的是,這是我迄今為止所擁有的:
public static void main(String[] args) {
System.out.println("Type in a sentence and click Enter:");
Scanner scanner = new Scanner(System.in);
String sentence = scanner.nextLine();
System.out.println(sentence);
String a[] = sentence.split(" ");
int n = 0; //n will be the variable for the amount of a word's appearances
for (int i = 0; i < a.length; i ) {
if (a[i]) { //Here i kinda want to find out how many times a certain word appears
}
}
}
uj5u.com熱心網友回復:
嘗試這個。
static List<String> onlyOnce(String sentence) {
return Arrays.stream(sentence.split(" "))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() == 1)
.map(Entry::getKey)
.toList();
}
public static void main(String[] args) {
System.out.println(onlyOnce("a b c d a c x y x"));
}
輸出:
[b, d, y]
uj5u.com熱心網友回復:
編輯(感謝@Pirate 的評論)Set順便說一下Set,您需要兩個而不是一個。
使用Set<String>它確保每個條目只出現一次。(但是,條目區分大小寫。因此,您可能希望在插入之前將它們全部轉換為大寫或小寫。)如果使用這種方法,for代碼中的回圈可能如下所示:
Set<String> onceWords = new HashSet<>();
Set<String> repeatedWords = new HashSet<>();
for( int i = 0; i < a.length; i ){
/* If the word was already seen, add it to repeated list. */
if( onceWords.contains( a[ i ] ) ) repeatedWords.add( a[ i ] );
onceWords.add( a[ i ] );
}
/* Now, remove all the repeated words from the distinct list. */
onceWords.removeAll( repeatedWords );
System.out.println( onceWords );
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/321771.html
上一篇:如何使用python根據串列中的一些關鍵元素拆分資料?
下一篇:具有特定字串名稱的多列的字串匹配
