2015-01-05 48 views
1

重复我有一个项目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); 

当我运行代码,所有的项目如输出中所示被复制到集合中。

enter image description here

不同的测试只用弦乐作品就好:

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); 

enter image description here

我可以用什么方法列表复制到一组不重复?是否有任何聚合操作,或者我必须编写自定义方法?

回答

5

您需要在Item类中实现equalshashCode方法。

+0

唐不要确定散列码不是强制性的。合约需要一个具有自定义“equals”的自定义哈希码,如果合约被破坏,“HashSet”可能会遗漏重复。 – chrylis

+0

@chrylis是的,你是对的。谢谢。 –

+1

谢谢你,现在我知道比昨天做的更多的java。 :) –

1

只是想我添加一个答案来说明如何我终于做到了(当然使用亚当的建议)

我加的equalshashCode方法的实现我的项目类:

@Override 
public boolean equals(Object obj) { 
    if(!(obj instanceof Item)) { 
     return false; 
    } 
    if(obj == this) { 
     return true; 
    } 

    Item other = (Item)obj; 
    if(this.getName().equals(other.getName()) 
      && this.getPrice() == other.getPrice() 
      && this.getCountryOfProduction().equals(other.countryOfProduction)) { 
     return true; 
    } else { 
     return false; 
    } 

} 

public int hashCode() { 
    int hash = 3; 

    hash = 7 * hash + this.getName().hashCode(); 
    hash = 7 * hash + this.getCountryOfProduction().hashCode(); 
    hash = 7 * hash + Double.valueOf(this.getPrice()).hashCode(); 
    return hash; 

} 
+1

您可以使用Objects.hash()和Object.equals()(自Java 7以来)或Guava的[Objects](http://docs.guava-libraries.googlecode)来简化/缩短上述代码。 com/git/javadoc/com/google/common/base/Objects.html)或Apache Commons Lang的[HashCodeBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/ lang3/builder/HashCodeBuilder.html)和[EqualsBuilder](http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html) –

+0

已注意,谢谢。 .. –

相关问题