使用String,Integer映射ArrayList和另一个内部Map

时间:2014-12-09 02:33:56

标签: java arraylist maps

编辑:我刚刚将TreeMap更改为HashMap,现在它运行起来很轻微,但仍然没有做我需要做的事情。

嘿,这是我长期坚持的事情。

我的目标是从文件sequence.txt中获取文本,然后调用传递扫描程序s和整数n的构造函数。在构造函数内部,我的目标是从n读取sequence个单词并将其保存在ArrayList中,然后内部映射应该能够在{{1}的序列之后立即获取单词单词并记住n + thisWord存在的次数。

所以,一个例子就是这些n(或5)个单词:

n

然后第六个可能是so an to me for,所以在原始地图中它将是:

map.put(arrList,innerMap);

其中arrList将包含and,而innerMap看起来像这样so, an, to, me, for

然后从那里开始添加每个新的,并且对于相同的序列,它将整数递增1。我会担心第二部分,但我甚至无法让我的代码工作,而且我也不知道我做错了什么。这是我的构造函数:

and | 1

更改为HashMap后,它现在打印出来:

public RandomWriter(Scanner s, int n) { Map<String, Integer> valMap = new HashMap<String, Integer>(); this.s = s; this.n = n; map = new HashMap<>(); ` Queue<String> tmp = new LinkedList<String>(); for (int i = 0; i < n; i++) { tmp.add(s.next()); } while (s.hasNext()) { ArrayList<String> tmpList = new ArrayList<String>(); tmpList.addAll(tmp); String current = s.next(); if (!valMap.containsKey(current)) { valMap.put(current, 1); } else { valMap.put(current, valMap.get(current + 1)); } tmp.add(current); tmp.remove(); map.put(tmpList, valMap); } // s.next(); System.out.println(map.keySet()); }

这是它正在进入的地图:

[[today, day], [me, and], [so, if], [in, for], [for, you], [top, in], [sent, receive], [for, many], [on, top], [or, on], [do, do], [side, so], [so, when], [under, on], [many, much], [to, do], [row, on], [for, when], [when, become], [dog, house], [toy, your], [many, is], [won, do], [become, inside], [why, to], [to, spell], [me, you], [school, under], [too, your], [hit, high], [can, do], [is, to], [for, how], [receive, get], [on, me], [animal, your], [to, animal], [inside, to], [your, for], [cat, many], [who, me], [spell, word], [do, cat], [house, live], [how, can], [your, who], [word, sent], [to, today], [canvas, word], [on, for], [low, ball], [which, many], [animal, if], [much, mouse], [live, living], [your, sent], [if, how], [high, kill], [ball, hit], [if, so], [in, side], [get, which], [you, if], [so, for], [do, if], [get, toy], [so, row], [if, to], [to, if], [win, won], [how, when], [inside, in], [dog, squirrel], [you, to], [and, you], [so, or], [word, school], [mouse, for], [for, why], [day, dog], [squirrel, fish], [your, if], [cat, dog], [for, which], [to, when], [more, for], [to, your], [which, cat], [living, canvas], [kill, win], [you, low], [when, inside], [fish, animal], [do, so], [many, more], [to, too], [when, to]]

1 个答案:

答案 0 :(得分:1)

这是错误的:

        if (!valMap.containsKey(current)) {
            valMap.put(current, 1);

        } else {
            valMap.put(current, valMap.get(current + 1));
        }

你可能想要:

        if (!valMap.containsKey(current)) {
            valMap.put(current, 1);

        } else {
            valMap.put(current, valMap.get(current) + 1);
        }

由于地图中包含密钥current,您希望将1添加到该密钥的值,而不是使用密钥current+1的值覆盖它,这可能不会存在。