在 JTextArea 中对单词进行排序

Sorting words in JTextArea

我的这个项目需要我将JTextArea中的用户输入按字典顺序排列,重复的单词只出现一次,然后在另一个JTextArea中输出。我的代码只做安排加上它在输出上加上括号。如何去除括号并确保重复的单词只出现一次?

这是我的代码。

      btnStat.addSelectionListener(new SelectionAdapter() {
        @Override
        public void widgetSelected(SelectionEvent e) {
            
            String text = textbox1.getText();
            String[] wordy = text.split(" ");
                 Arrays.sort(wordy);
                 textbox8.setText("Sorted words: \n" +Arrays.toString(wordy));
            }
       }
     }

这是一个例子textbox1.setText("this is an example example") 代码输出 [an, example, example, is, this] 应该输出 an, example, is, this

使用SortedSet,这样你就可以去掉重复的单词。

String text = "this is an example example";
SortedSet<String> set = new TreeSet<>(Arrays.asList(text.split(" ")));
System.out.println(set);

如果有帮助请告诉我:)

您可以使用SortedSet,它既会按自然顺序对元素进行排序,又会去除重复元素。要摆脱括号,不要依赖 toString 方法,而是加入元素,例如使用流和加入收集器。 代码示例:

        String text = "this is an example example";
        
        String[] wordy = text.split(" ");
        SortedSet<String> set = new TreeSet<String>();
        set.addAll(Arrays.asList(wordy));
        System.out.println("Sorted words: \n" + set.stream().collect(Collectors.joining(", ")));