4

大家好,我正在尝试打印所有重复的元素,这工作正常,但输出不按顺序排列(来自用户输入或来自文本文件)。我想按顺序打印所有元素(不打印重复项)。我怎么做?代码来自此Find the duplicate elements in arraylist 并显示 感谢@Cory Kendall 的代码。

**********更新的问题:代码现在与LinkedHashMap完美配合。现在我希望用数字项目符号(即 1. name1 = 2 )递增地打印输出。谢谢

List<String> strings = new ArrayList<String>();
// suppose datas are entered by user incrementally or from a text files.

Map<String, Integer> counts = new HashMap<String, Integer>();

for (String str : strings) {
    if (counts.containsKey(str)) {
        counts.put(str, counts.get(str) + 1);
    } else {
        counts.put(str, 1);
    }
}

for (Map.Entry<String, Integer> entry : counts.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}
4

4 回答 4

6

如果您想记住地图中的插入顺序,您需要使用LinkedHashMap. 在您的情况下,您必须更换

Map<String, Integer> counts = new HashMap<String, Integer>();

Map<String, Integer> counts = new LinkedHashMap<String, Integer>();
于 2013-01-17T09:51:36.857 回答
3

HashMap未排序或排序,LinkedHashMap如果您关心则insertion order使用,或者TreeMap如果您关心则使用natural order

于 2013-01-17T09:51:46.660 回答
2
public class FindDup {
    public static void main(String[] args) {
        String str[] = { "yogi", "ram", "ram", "yogi", "yogi", "yogi", "raju", "raju", "ram", "yogi", };
        Map<String, Integer> map = new HashMap<String, Integer>();
        for (String s : str) {
            if (map.containsKey(s)) {
                map.put(s, map.get(s) + 1);
            } else {
                map.put(s, 1);
            }
        }
        for (Entry<String, Integer> e : map.entrySet()) {
            System.out.println(e.getKey() + "---" + e.getValue());

        }
    }
}
于 2016-03-18T08:14:15.270 回答
1

LinkedHashMap将保持顺序。

Map<String, Integer> counts = new LinkedHashMap<String, Integer>();

关于LinkedHashMap

Map 接口的哈希表和链表实现,具有可预测的迭代顺序。此实现与 HashMap 的不同之处在于它维护一个双向链表,该列表贯穿其所有条目。这个链表定义了迭代顺序,通常是键插入映射的顺序(插入顺序)。

于 2013-01-17T09:51:51.187 回答