-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;
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 2
    Does this answer your question? [Sort a list that contains a custom class](https://stackoverflow.com/questions/10396970/sort-a-list-that-contains-a-custom-class) – Duelist May 07 '20 at 20:34
  • https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/Arrays.html#sort(T%5B%5D,java.util.Comparator) – Lesiak May 07 '20 at 20:35

1 Answers1

0
List<Word> list = getWordList();
list.sort(Comparator.comparing(w -> w.getWord()));
return list.toArray();
fram
  • 1,551
  • 1
  • 7
  • 7
  • 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. – borchvm May 08 '20 at 09:23
  • 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 `String`s 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 `Word`s, compares each one's `getWord()` output. I've simplified this with Java 8's lambda `->` expression. I hope that helps! – fram May 08 '20 at 15:31