-1

我想检查 a 的值是否LinkedHashmap已经包含一个字符串,如果没有,将它添加到 ArrayList。 windowSize介于 1 和 7 之间(预定义)

String wholeString = "HausA HausB";

final Map<String, ArrayList<String>> generateMap = new LinkedHashMap<String, ArrayList<String>>();
final int limit = wholeString.length() - windowSize;
    for (int i = 0; i < limit; i++) {
        String first = wholeString.substring(i, i + windowSize);
        String second = wholeString.substring(i + windowSize, i
                + windowSize + 1);

        int endKey = i + windowSize;
        if (!generateMap.containsKey(first)) {
            generateMap.put(wholeString.substring(i, endKey),
                    new ArrayList<String>());
        }
                    //check here if the String 'second' is already mapped to the key'
                    if (i < limit && !generateMap.get(first).equals(second)) {
            generateMap.get(first).add(second);
        } else {
            generateMap.get(first).add(null);
        }
    }

   for (Entry<String, ArrayList<String>> e : generateMap.entrySet()) {
        System.out.println(e.getKey() + " -> " + e.getValue()+ "\n");
   }

现在的输出:

HausA -> [ ]
ausA  -> [H]
usA H -> [a]
sA Ha -> [u]
A Hau -> [s]
Haus  -> [B]
HausB -> [ ]

应该如何:

HausA -> [ ]
ausA  -> [H]
usA H -> [a]
sA Ha -> [u]
A Hau -> [s]
Haus  -> [A,B] //<---
HausB -> [ ]

感谢您的赞赏帮助。

4

1 回答 1

1

看看这个怎么搭配...

final String wholeString = " HausA HausB";
final Map<String, Set<String>> generateMap = new LinkedHashMap<String, Set<String>>();
final int windowSize = 5;

final int limit = wholeString.length() - windowSize;
for (int i = 0; i < limit; i++) {
  final int endKey = i + windowSize;
  final String
      first = wholeString.substring(i, endKey),
      second = wholeString.substring(endKey, endKey + 1);
  if (!generateMap.containsKey(first))
    generateMap.put(first, new HashSet<String>());
  generateMap.get(first).add(second);
}

for (Entry<String, Set<String>> e : generateMap.entrySet()) {
  System.out.println(e.getKey() + " -> " + e.getValue());
}
于 2012-04-26T21:25:11.160 回答