如何在LinkedList中搜索特定单词并返回它在列表中的位置以及出现的次数

时间:2018-11-08 12:43:39

标签: java java-8 linked-list

我遇到一个问题,我需要搜索已创建的链接列表,并输出指定单词出现的次数以及该单词出现在列表中的位置。所有这些都在Java GUI中完成,在Java GUI中,使用文本字段输入特定单词。我在代码中遇到麻烦的特定按钮是已经在其中添加代码的“ searchList”按钮,但是我仍然没有得到所需的结果。

任何帮助,将不胜感激!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.LinkedList;
import java.util.TreeMap;

public class Main {

public static void main(String[] args) {
FilledFrame frame = new FilledFrame();

frame.setVisible( true );
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setTitle("Word List");
}
}

class  FilledFrame extends JFrame{
JLabel     addWord;
JTextField addW;
JTextArea wordArea;

// Creating linked list
private LinkedList<String> wordList = new LinkedList();

public FilledFrame(){

    //Create JTextArea
    wordArea                = new JTextArea();

    //Create all the buttons, JLabel and the JPanel
    JButton addButton       = new JButton("Add Word");
    JButton specifiedLetter = new JButton("Display Specific Letter");
    JButton searchList      = new JButton("Search List");
    JButton removeLastOcc   = new JButton("Remove Last");
    JButton removeAll       = new JButton("Remove All Word Occurrence's ");
    JButton clearList       = new JButton("Clear List");

    JPanel panel            = new JPanel();

    //Add buttons and label to the window

    panel.add(addButton);
    add(panel, BorderLayout.NORTH);

    panel.add(specifiedLetter);
    add(panel, BorderLayout.NORTH);

    panel.add(searchList);
    add(panel, BorderLayout.NORTH);

    panel.add(removeLastOcc);
    add(panel, BorderLayout.NORTH);

    panel.add(removeAll);
    add(panel, BorderLayout.NORTH);

    panel.add(clearList);
    add(panel, BorderLayout.NORTH);


    //Create all Text Fields and Labels
     addWord          = new JLabel("Enter word");

     addW             = new JTextField(20);

    JPanel panel1     = new JPanel();

    //Add labels and text fields to the window
    panel1.add(addWord);
    add(panel1, BorderLayout.SOUTH);
    panel1.add(addW);
    add(panel1, BorderLayout.SOUTH);


    //Add JTextArea to the center and make sure user cannot type into it
    add(wordArea, BorderLayout.CENTER);
    wordArea.setEditable( false );


    //  Action listeners for each button

    addButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            wordList.add((addW.getText()));
            wordArea.setText(" The word " + addW.getText() + " was added to the list ");
            System.out.println(wordList);
        }
    });

    specifiedLetter.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {


        }
    });

    //The button I am having trouble with

    searchList.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String showWord = "";
            TreeMap<String, Integer> treeMap = new TreeMap<>();

            if ((addW.getText()).length() < 1){
               for(String word : wordList)
               {
                    treeMap.put(word, 1);
                    treeMap.keySet().contains(word);

                    if (treeMap.containsKey(word)) {
                        treeMap.replace(word, treeMap.get(word)+1);
                    }
                    else{
                        treeMap.put(word, 1);
                    }
               }

                wordArea.setText(showWord);
                for (String word: wordList){
                    System.out.println(" This word appears " + word);
                }

            }

            }


        });

2 个答案:

答案 0 :(得分:2)

您可以使用Java 8中的Collector用一条简单的代码替换您编写的整个逻辑:

 Map<String, Long> collect = list.stream()
          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

在这里,您会得到一个Map<String, Long>,其中的key是单词,并重视重复的次数。

要找到它出现的位置,可以遍历列表并从刚创建的地图中找到该单词的首次出现。

答案 1 :(得分:0)

尝试以下解决方案:

Map<String, List<Integer>> map = new HashMap<>();
IntStream.range(0, list.size())
         .forEach(i -> {
             map.computeIfAbsent(list.get(i), s -> new ArrayList<>()).add(i);
         });

它将所有索引存储在列表中。现在,您可以通过map.get(str)轻松获得索引,也可以通过map.get(str).size()轻松获得出现次数。

请注意,此解决方案可一次执行所有操作。因此,您不需要重复两次任何集合。