[英]Find duplicates in array list using Map<String, Integer> with input order
Hi everyone I am trying to print all the duplicated elements, this works fine but the outputs are not in order (either from user input or from the text file). 大家好,我正在尝试打印所有重复的元素,效果很好,但是输出的顺序不正确(无论是来自用户输入还是来自文本文件)。 I want to print all elements with order (duplicates are not printed).
我想按顺序打印所有元素(不打印重复项)。 How do I do that?
我怎么做? The codes are from this Find the duplicate elements in arraylist and display Thanks @Cory Kendall for the codes.
代码来自此。 在arraylist中查找重复的元素,并显示 @@ Cory Kendall的代码。
**********updated question: the code now works perfect with LinkedHashMap. **********更新了问题:该代码现在可以与LinkedHashMap完美配合。 Now I want the outputs to be printed with number bullets (ie, 1. name1 = 2 ) incrementally.
现在,我希望输出以数字项目符号(即1. name1 = 2)递增地打印。 Thanks
谢谢
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());
}
If you want to remember insertion order in your Map, you need to use LinkedHashMap
. 如果您想记住地图中的插入顺序,则需要使用
LinkedHashMap
。 In your case you have to replace 在您的情况下,您必须更换
Map<String, Integer> counts = new HashMap<String, Integer>();
with 与
Map<String, Integer> counts = new LinkedHashMap<String, Integer>();
HashMap
没有排序或排序,如果您关心insertion order
,请使用LinkedHashMap
如果您关心natural order
,请使用TreeMap
。
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());
}
}
}
A LinkedHashMap will retain order. LinkedHashMap将保留顺序。
Map<String, Integer> counts = new LinkedHashMap<String, Integer>();
About LinkedHashMap
: 关于
LinkedHashMap
:
Hash table and linked list implementation of the Map interface, with predictable iteration order.
Map接口的哈希表和链表实现,具有可预测的迭代顺序。 This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries.
此实现与HashMap的不同之处在于,它维护贯穿其所有条目的双向链接列表。 This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).
此链表定义了迭代顺序,通常是将键插入映射的顺序(插入顺序)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.