重复我有一个项目List
名为items
并使用我复制此列表的Set
:复制对象复制到另一个集合的集合,而无需使用聚合操作
List<Item> items = new ArrayList<>();
items.add(new Item("Suremen Body Spray", 1900, 45));
items.add(new Item("HP wireless mouse", 5500, 5));
items.add(new Item("UWS USB memory stick", 1900, 8));
items.add(new Item("MTN modem", 1900, 45));
items.add(new Item("MTN modem", 1900, 45));
Collection<Item> noDups = new LinkedHashSet<Item>(items); //Copy items to noDups
//Print the new collection
noDups.stream()
.forEach(System.out::println);
当我运行代码,所有的项目如输出中所示被复制到集合中。
不同的测试只用弦乐作品就好:
List<String> names = new ArrayList<>();
names.add("Eugene Ciurana");
names.add("Solid Snake");
names.add("Optimus Prime");
names.add("Cristiano Ronaldo");
names.add("Cristiano Ronaldo");
Collection<String> itemCollection = new HashSet<String>(names);
itemCollection.stream()
.forEach(System.out::println);
我可以用什么方法列表复制到一组不重复?是否有任何聚合操作,或者我必须编写自定义方法?
唐不要确定散列码不是强制性的。合约需要一个具有自定义“equals”的自定义哈希码,如果合约被破坏,“HashSet”可能会遗漏重复。 – chrylis
@chrylis是的,你是对的。谢谢。 –
谢谢你,现在我知道比昨天做的更多的java。 :) –