直接上代码,这段代码 直接copy运行看效果就行。 使用的时候直接把string数组替换成自己的就可以了
public static void main(String[] args) { Map<String, Integer> map = new HashMap<String, Integer>(); String[] array = new String[] { "ff", "BB", "cc", "dd", "AA", "BB", "cc", "dd", "AA", "BB", "AA" }; for (String str : array) { Integer num = map.get(str); num = null == num ? 1 : num + 1; map.put(str, num); } if (array.length != map.size()) { System.out.println("存在相同的元素及重复个数!"); } Set set = map.entrySet(); Iterator<Entry> it = set.iterator(); List<String> sList = new ArrayList<String>(); while (it.hasNext()) { Entry<String, Integer> entry = (Entry<String, Integer>) it.next(); String key = entry.getKey(); Integer value = entry.getValue(); System.out.println("String :" + key + " num :" + value); if (value > 1) sList.add(key); } System.out.println("============相同元素的下标======================"); List<ArrayList<Integer>> indexArr = new ArrayList<ArrayList<Integer>>(); for (String s : sList) { ArrayList<Integer> aIntegers = new ArrayList<Integer>(); for (int i = 0; i < array.length; i++) { if (array[i].equals(s)) { aIntegers.add(i); } } if (aIntegers.size() > 0) indexArr.add(aIntegers); } System.out.println(indexArr); }效果如下:
存在相同的元素及重复个数! String :dd num :2 String :AA num :3 String :BB num :3 String :ff num :1 String :cc num :2 相同元素的下标========== [[3, 7], [4, 8, 10], [1, 5, 9], [2, 6]]