我目前有这个代码:
String foxes = "The,Quick,Brown,Fox,Jumped,Over,The,Lazy,Dog.";
System.out.println(" Here is the string unedited: " + foxes);
String lowerCase = foxes.toLowerCase() .replaceAll("[\.:;'\"!\?]", " ");
System.out.println(" Here is the string (no caps + no punctuation): " + lowerCase);
List<String> foxesList = new ArrayList<String>(Arrays.asList(lowerCase.split(",")));
简而言之,此代码创建一个 String
,使其不区分大小写,然后将其转换为数组。
我现在需要找到数组中每个重复项的位置,并且我目前知道它与嵌套循环有关。重复项是出现 2 次的 The 。我需要知道这两个重复项的位置。
最佳答案
您可以使用HashMap<String, int[]
:
Map<String, ArrayList<Integer>> map = new HashMap<>();
for (int i = 0; i < foxesList.size(); i++) {
String fox = foxesList.get(i);
ArrayList<Integer> list = map.get(fox);
if (list == null) {
list = new ArrayList<>();
list.add(i);
map.put(fox, list);
} else {
list.add(i);
}
}
在此映射中,对于每个狐狸名称,您将存储该狐狸的所有索引。如果列表有多个元素,则意味着存在重复项。
关于java - JAVA如何获取数组重复项的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40126064/