查找list中的重復數據,並得到不重復數據索引位置


public static void main(String[] args) {
	List<String> strLs = new ArrayList<String>();
	strLs.add("香蕉");
	strLs.add("蘋果");
	strLs.add("蘋果");
	strLs.add("橘子");
	strLs.add("橘子");
	strLs.add("橘子");
	strLs.add("哈密瓜");
	strLs.add("西瓜");

	same(strLs);
}

public static List<Integer> same(List<String> list) {
	Map<String, String> map = new HashMap<String, String>();
	for (int i = 0; i < list.size(); i++) {
		String key = list.get(i);
		String old = map.get(key);
		if (old != null) {
			map.put(key, old + "," + (i + 1));
		} else {
			map.put(key, "" + (i + 1));
		}
	}
	Iterator<String> it = map.keySet().iterator();
	List<Integer> list2 = new ArrayList<>();
	StringBuffer buffer = new StringBuffer();
	while (it.hasNext()) {
		String key = it.next();
		String value = map.get(key);
		if (value.indexOf(",") == -1) {
			System.out.println(key + "不重復,行: " + value);
			buffer.append(value).append(",");
		}
	}
	String string = buffer.deleteCharAt(buffer.length()-1).toString();
	
	String[] split = string.split(",");
	for (String string2 : split) {
		list2.add(Integer.parseInt(string2.trim()));
	}
	Collections.sort(list2);
	return list2;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM