java - 从文本中找出一个单词的所有行号

标签 java hashmap

我写了一个方法,它必须找到word的所有行号,然后打印它们。
输入必须在后面

 Word:works/*(just one in file)*/Line Number:[7]  
 Word:run                      Line Number:[3,7,9]
 Word:we                       Line Number[5,8]   

这就是我的方法

HashMap m2 = new HashMap();

public void addLine(FileReader file) throws IOException {
        try {
            LineNumberReader lnR = new LineNumberReader(file);
            StringBuilder sb = new StringBuilder();
            String line = lnR.readLine();

            while (line != null) {
                String[] words = line.split("\\W+");
                for (int i = 0; i < words.length; i++) {
                    if (m2.get(words[i].toLowerCase()) == null) {
                        m2.put(words[i].toLowerCase(), "[" + lnR.getLineNumber() + " ");
                    } else {
                        int x = lnR.getLineNumber();
                        m2.put(words[i].toLowerCase(), " " + x + "]");
                    }
                }
                sb.append(System.lineSeparator());
                line = lnR.readLine();
            }
            lnR.close();
        } catch (IOException ex) {
            System.out.println("Error reading file '" + file + "'");
        }
    }

还有我的主要方法。

public static void main(String[] args) throws IOException {
addLine(new FileReader("C:/Users/Text.txt"));
Map<String, String> sorted1 = new TreeMap<String, String>(m2);
        for (Object key : sorted1.keySet()) {
            System.out.println("Word: " + key + "\tLine Number: " m2.get(key));
        }
}

我的方法给出了错误的输出。

Word: write     Line Number:  [9
Word: we    Line Number:  8]

我该如何解决这个问题?
感谢所有读者。

最佳答案

试试这个。

static Map<String, List<Integer>> addLine(Reader reader) {
    LineNumberReader r = new LineNumberReader(reader);
    return r.lines()
        .filter(line -> line.length() != 0)
        .flatMap(line -> Arrays.stream(line.split("\\W+")))
        .map(word -> word.toLowerCase())
        .collect(Collectors.groupingBy(word -> word,
            TreeMap::new,
            Collectors.mapping(word -> r.getLineNumber(), Collectors.toList())));
}

public static void main(String[] args) throws IOException {
    try (Reader reader = new FileReader("C:/Users/Text.txt")) {
        for (Entry<String, List<Integer>> e : addLine(reader).entrySet())
            System.out.println("Word: " + e.getKey() + "\tLine Number: " + e.getValue());
    }
}

关于java - 从文本中找出一个单词的所有行号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34475599/

相关文章:

java - 迭代并发Hashmap

java - 获取 xml 元素值中的 HTML 或 XHTML 文本

JavaFX 边框不适合具有自定义形状的节点

java - 树中的所有节点都没有扩展

java - 显示 JList 内的值 -

java - mybatis中动态使用HashMap进行参数映射

java - 如何在 HashMap 中添加多个具有相同键的相同类型的对象

java - HashMap<int[],string> 通过考虑它们的值来映射整数数组

java - Hibernate PostgreSQL OneToOne 关系首先触发子查询

java - 如何使用 Hibernate 根据现有列填充集合