Home > Mobile >  How do i find and output all the words that appear only once?
How do i find and output all the words that appear only once?

Time:10-19

I have to find words that appear only once (no less, no more) and output them. Unfortunately, this is what i have so far:

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
            }
        }
    }

CodePudding user response:

Try this.

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"));
}

output:

[b, d, y]

CodePudding user response:

Edit (Thanks to @Pirate's comment) In the Set way, instead of one Set, you will need two.

Use Set<String> which ensures that each entry appears only once. (However, entries are case-sensitive. So, you may want to convert them all to upper or lower case before inserting.) If you use this approach, the for loop in your code may look like this:

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 );
  • Related