-1

So I have a word class and the word class stores both a word and a number, the word being the... well... word and the number being the number of times it occurs in a string. I want to return an array of all the words in alphabetical order and I know that Arrays.sort is a thing but I don't know how to sort the classes themselves.

Could someone help me sort them by both alphabetical order and numerical?

Word class below

import java.io.File;
import java.util.Scanner;
public class Word
{
    private String word;
    private int count;

    public Word(String str)
    {
        word = str;
        count = 1;
    }

    public String getWord()
    {
        return word;
    }

    public int getCount()
    {
        return count;
    }

    public void increment()
    {
        count++;
    }

    public String toString()
    {
        String result = String.format(count + "\t" + word);
        return result;
    }
}
2

1 Answer 1

0
List<Word> list = getWordList();
list.sort(Comparator.comparing(w -> w.getWord()));
return list.toArray();
Sign up to request clarification or add additional context in comments.

2 Comments

While this code may provide a solution to the question, it's better to add context as to why/how it works. This can help future users learn, and apply that knowledge to their own code. You are also likely to have positive feedback from users in the form of upvotes, when the code is explained.
Thank you borchvm, I'm new to SO so I appreciate it. The idea with my code is that List.sort() can either sort by the elements' "natural ordering", or it can accept a Comparator to specify how to compare two elements. We want to compare the Strings returned by getWord(). Pre-Java 8 we'd have had to provide an anonymous class that implements Comparator with an implementation of compare() method that, given two Words, compares each one's getWord() output. I've simplified this with Java 8's lambda -> expression. I hope that helps!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.