Skip to content
Advertisement

How do I break up words in a String ArrayList in Java and then reverse them?

The title may sound confusing.

Simply, I have a file that have text inside of it. I used a scanner to read that text. I stored that text into an ArrayLists that is a String. The problem I have is that I need to make a method reverses the text in that ArrayList. The text does reverse, but not completely. I need the words to be in reverse order too, but my String ArrayList is broken down in sentences.

Therefore, I need help reaching in each ArrayList and breaking those words up into other ” ” and then put them in my method so it can reverse the words properly.

What I want to be accomplished is first breaking apart the lines and reverse the words. The difficult part is still returning the whole text in lines. My professor recommended creating helper methods to solve this. Please help.

JavaScript

The current output:

JavaScript

The Desired Output:

JavaScript

Advertisement

Answer

If you want to retain the sentences, but have the words in each sentence reversed you could do:

JavaScript

If you are trying to obtain a List of the words in reverse order:

The problem is that you are adding lines to your List, and then printing those lines in reverse, but not the words. You can easily fix this by splitting the line on white space and adding all of those tokens to the List. You can do so using the split() method:

JavaScript

However we can do this more elegantly with Collections.addAll:

JavaScript

Or when you’re printing you can split it into words there:

JavaScript

Or java 8+:

JavaScript

Which will use the lines() method to take a stream of the lines, split them into words, reverse them, and then collect them to a List, and then reverse them

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement