2

I am trying to append a LinkedHashSet to a textArea in java 8. The code below works but it doesn't add the content line by line, and it adds them all in one line.

Code:
    textArea.setText(textArea.getText() + linkedHashSet);
    [   lin1,       line2,      line3,      line4]

I am looking to append them to the textArea as listed below

line1
line2
line3
line4

2 Answers 2

3

Since this is Java 8, you can use:

textArea.setText( textArea.getText()
                  + String.join( System.lineSeparator(), linkedHashSet ));

The various forms of String.join, this one accepting a delimiter and an Iterable, let you join together the elements' string representations with a delimiter - in this case a line separator.

Usually, if your Iterable (set, list) has elements "A", "B" and "C", and you want to join them with ,, you use:

String.join( ",", myIterable );

And this will give you:

A,B,C

If the first parameter was ---BIG DELIMITER---, then you would get:

A---BIG DELIMITER---B---BIG DELIMITER---C

But in our case, we put in the System.lineSeparator(), which means that your strings will be separated by \n (on Linux machines), or \r\n (on Windows machines). This means that each of the values will be on a separate line:

A
B
C
2
  • Thanks so much that works. But can you give me few lines that explain your code from String.Join. Sure String.Join is the obvious, but how does it work with system.lineSeparator
    – Moe
    Sep 12, 2015 at 18:40
  • 1
    @Moe I added an explanation to the answer. Sep 12, 2015 at 18:47
1

You first have to understand what your code actually does. I am assuming in this explanation that lnkedHashSet is a LinkedHashSet of String objects.

  1. textArea.getText() is called to get current textarea value
  2. linkedHashSet.toString() is called to produce the textual version of linkedHashSet. That method returns a string that contains a square bracket, comma-separated list of Strings in the linkedHashSet, and a final square bracket.
  3. The text area value and hash set strings are concatenated into a single string
  4. textArea.setText(String) sets the text area to the new single string

So the problem is that linkedHashSet.toString() doesn't know you want an EOL added after every value, and there is no way to make it do that.

You can do the following (works for any Java version >= 5):

StringBuilder sb = new StringBuilder;
for (String item : linkedHashSet) {
  sb.append(item).append('\n');
}
textArea.setText(sb.toString());
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.