Java 您如何在 ArrayList 中为唯一值保留原始顺序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18864441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you keep the original order in an ArrayList for unique values?
提问by mvitagames
For example if i want to preserve the order of the string that appear first, but I also want the second occurrence of the duplicate to follow after the first one on the list of output. for example if I added: arrlist.add("bob"); arrlist.add("pat"); arrlist.add("tan"); arrlist.add("bob"); arrlist.add("mat"); arrlist.add("cat"); arrlist.add("dog"); arrlist.add("cat");
例如,如果我想保留首先出现的字符串的顺序,但我还希望在输出列表中的第一个之后出现第二次重复。例如,如果我添加: arrlist.add("bob"); arrlist.add("拍"); arrlist.add("tan"); arrlist.add("鲍勃"); arrlist.add("mat"); arrlist.add("猫"); arrlist.add("狗"); arrlist.add("猫");
I want the output to be
我希望输出是
String = bob
String = bob
String = pat
String = tan
String = mat
String = cat
String = cat
String = dog
This is my code:
这是我的代码:
package com.tutorialspoint;
import java.util.ArrayList;
public class ArrayListDemo {
public static void main(String[] args) {
// create an empty array list with an initial capacity
ArrayList<String> arrlist = new ArrayList<String>();
// use add() method to add elements in the list
arrlist.add("bob");
arrlist.add("pat");
arrlist.add("tan");
arrlist.add("bob");
arrlist.add("mat");
arrlist.add("cat");
arrlist.add("dog");
arrlist.add("cat");
// let us print all the elements available in list
for (String number : arrlist) {
System.out.println("String = " + number);
}
// retrieves element at 4th postion
String retval=arrlist.get(3);
System.out.println("Retrieved element is = " + retval);
}
}
采纳答案by anguyen
If you want the items to come out in sorted order (according to alphabetical order), take a look at a priority queue.
如果您希望项目按排序顺序(按字母顺序)出现,请查看优先队列。
Every time you add an item, it is added based off of the comparator. The comparator decides the ordering (alphabetical, by length, whatever).
每次添加项目时,都会根据比较器添加它。比较器决定排序(按字母顺序、按长度等)。
Then, when you print and remove items from the front of the queue, your items will print off in order.
然后,当您打印和删除队列前面的项目时,您的项目将按顺序打印。
回答by Kayaman
You can get the index of a value in the list with indexOf(yourString). You can use that to check if the entry exists and insert the value after that one. See the javadocsfor more information.
您可以使用 indexOf(yourString) 获取列表中某个值的索引。您可以使用它来检查条目是否存在并在该条目之后插入值。有关更多信息,请参阅javadoc。
Something along the lines of
类似的东西
if(arrlist.indexOf(myString) == -1) // Not found
arrlist.add(myString)
else
arrlist.add(arrlist.indexOf(myString), myString)
Well there I did it, wrote you the code...shame on me.
好吧,我做到了,给你写了代码……我真丢脸。
回答by Nicole
That's not really "preserving", because in a raw sense, you really did input bob
firstand fourth, not firstand second.
这并不是真正的“保留”,因为从原始意义上讲,您确实输入了bob
first和第四个,而不是first和second。
There are no native datasets that I'm aware of that accomplish this, however, you can achieve this with a LinkedHashMap
(preserves the order of the first time a key was entered) where the value is the count of the number of times the item was added:
我知道没有本地数据集可以完成此操作,但是,您可以使用LinkedHashMap
(保留第一次输入键的顺序)来实现此目的,其中值是项目出现的次数的计数添加:
- Create an
add
method that gets the value from the hash map or defaults to 0. Increment it. Put it on the hash map again. - When reading the list, iterate over the map entry set and then output the key once for the number in value.
- 创建一个
add
从哈希映射中获取值或默认为 0 的方法。增加它。再次将其放在哈希映射上。 - 读取列表时,遍历映射条目集,然后为 value 中的数字输出一次键。
Example
例子
public static class ReorderingList {
private LinkedHashMap<String, Integer> items =
new LinkedHashMap<String, Integer>();
public void add(String item) {
Integer value = items.get(item);
if (value == null) value = 0;
value++;
items.put(item, value);
}
public List<String> asList() {
List<String> result = new ArrayList<String>();
for(Map.Entry<String, Integer> entry : items.entrySet()) {
for (int i=0; i < entry.getValue(); i++) {
result.add(entry.getKey());
}
}
return result;
}
}
Test
测试
public static void main(String[] args) {
ReorderingList rlist = new ReorderingList();
rlist.add("bob");
rlist.add("pat");
rlist.add("tan");
rlist.add("bob");
rlist.add("mat");
rlist.add("cat");
rlist.add("dog");
rlist.add("cat");
List<String> arrlist = rlist.asList();
// let us print all the elements available in list
for (String number : arrlist) {
System.out.println("String = " + number);
}
// retrieves element at 4th postion
String retval=arrlist.get(3);
System.out.println("Retrieved element is = " + retval);
}
Test output:
测试输出:
String = bob
String = bob
String = pat
String = tan
String = mat
String = cat
String = cat
String = dog
Retrieved element is = tan
Working ideone example
工作ideone示例
回答by Steven Schlansker
If you can use Guava, you could consider using a LinkedHashMultiset, which will directly solve your problem without needing to adapt it to e.g. the LinkedHashMap as proposed by NickC.
如果您可以使用番石榴,您可以考虑使用LinkedHashMultiset,它将直接解决您的问题,而无需将其调整为例如 NickC 提出的 LinkedHashMap。
回答by Rhuan Karlus
Just use Collections.sort(myArrayList);
. You're using an ArrayList
of String
, therefore if you want to use some other kind of object, you'll have to implement the compare()
method inside your object to use the Collections.sort()
.
只需使用Collections.sort(myArrayList);
. 您正在使用ArrayList
of String
,因此如果您想使用其他类型的对象,则必须compare()
在对象内部实现该方法才能使用Collections.sort()
.
Take a look at Object Orderingfor a better explanation.
查看对象排序以获得更好的解释。