0

I have built an ArrayList of strings from two sources:

Path p1 = Paths.get("C:/Users/Green/documents/dictionary.txt");
Scanner sc = new Scanner(p1.toFile()).useDelimiter("\\s*-\\s*");
ArrayList al = new ArrayList();

while (sc.hasNext()) {          
    String word = (sc.next());      
    al.add(word);
    al.add(Translate(word));
}

The array is made up of a word from a text file dictionary read one line at a time. The second is a translation of the word. The translation Translate is a Java method that now returns a string. so I am adding two strings to the array list for as many lines that there are in the dictionary.

I can print the dictionary out and the translations....but the printout is unhelpful as it prints all the words and then all the translations....not much use to quickly look up.

for(int i=0;i<al.size();i++){
    al.forEach(word ->{ System.out.println(word); }); 
}

Is there a way that I can either manipulate the way I add the strings to the ArrayList or how I manipulate after so that I can retrieve one word and its translation at a time.

Ideally I want to be able to sort the dictionary as the file I receive is not in alphabetic order.

2 Answers 2

1

I am not sure why you have to use ArrayList data structure as it is required or not.

I would suggest you use the Map for this kind of dictionary data. Map data structure will manage your data as a key which is your original word and a value which is a translated word.

Here is a simple example:

 Path p1 = Paths.get("C:/Users/Green/documents/dictionary.txt");
 Scanner sc = new Scanner(p1.toFile()).useDelimiter("\\s*-\\s*");

 Map<String, String> dic = new HashMap<String, String>();

 while (sc.hasNext()) {      
    String word = (sc.next());
    dic.put(word, Translate(word));
 }


//print out from dictionary data

for(Map.Entry<String, String> entry: dic.entrySet()){
    System.out.println(dic.getKey() + " - "  + dic.getValue());
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can use object like this

class Word {
    String original;
    String translation;

    public Word(String original, String translation) {
        this.original = original;
        this.translation = translation;
    }
}

Put words to list:

while (sc.hasNext()) {          
        String word = (sc.next());
        al.add(new Word(word, Translate(word)));
}

And then:

for (Word word : al) {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.