Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alphabetize individual strings from list - Java

I want to read in a list of words. Then I want alphabetize each of the characters within each word such that I have an entire list of words where each letter is alphabetized. For example if I wanted to read in "cat" "dog" "mouse" from a text file I would have [a,c,t], [d,g,o], and [e,m,o,s,u].

I'm implementing this in Java. I thought about a linked list or some other Collection but I'm not really sure how to implement those with respect to this. I know it's not as simple as converting each string to a char array or using array list. (I already tried those)

Does anyone have any suggestions or examples of doing this?

Basically, I'm just trying to get better with algorithms.

 public class AnagramSolver1 {

static List<String> inputList = new ArrayList<String>();

public static void main(String[] args) throws IOException {

    List<String> dictionary = new ArrayList<String>();
    BufferedReader in = new BufferedReader(new FileReader("src/dictionary.txt"));
    String line = null;
    Scanner scan = new Scanner(System.in);

    while (null!=(line=in.readLine()))
    {
       dictionary.add(line);
    }
    in.close();

    char[] word;


    for (int i = 0; i < dictionary.size(); i++) {
        word = inputList.get(i).toCharArray();
        System.out.println(word);
    }
like image 947
David Avatar asked Jul 12 '26 08:07

David


1 Answers

If you have a String called word, you can obtain a sorted char[] of the characters in word via Arrays.sort

char[] chars = word.toCharArray();
Arrays.sort(chars);

I assume you would want to repeat this process for each member of a collection of words.

If you're interested in knowing what happens behind the scenes here, I would urge you to take a look at the source.

like image 135
arshajii Avatar answered Jul 15 '26 02:07

arshajii