检查String是否已经在LinkedHashMap中(作为值)

时间:2012-04-26 20:04:39

标签: java string duplicates treemap

我想检查LinkedHashmap的值是否已经包含String,如果没有,则将其添加到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 -> [ ]

感谢您的帮助。

1 个答案:

答案 0 :(得分: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());
}