Java哈希集删除重复项
下面的函数返回产品列表。产品列表应该是唯一的 vector ServAttributes存储自定义类的对象。自定义类有一个函数getProduct,该函数提供可能包含重复项的产品名称 我是否需要滚动整个向量,检索对象,调用函数getProduction并添加到哈希集以删除重复的产品?Vector有时存储400个自定义类的对象。有没有什么简单的方法可以实现下面的功能Java哈希集删除重复项,java,Java,下面的函数返回产品列表。产品列表应该是唯一的 vector ServAttributes存储自定义类的对象。自定义类有一个函数getProduct,该函数提供可能包含重复项的产品名称 我是否需要滚动整个向量,检索对象,调用函数getProduction并添加到哈希集以删除重复的产品?Vector有时存储400个自定义类的对象。有没有什么简单的方法可以实现下面的功能 private Vector<ServAttributes> ServAttributes = null; publi
private Vector<ServAttributes> ServAttributes = null;
public HashSet<String> retProduct() {
HashSet<String> Produset = new HashSet<String>();
for (int x = 0; x < ServAttributes.size(); x++) {
ServAttributes record = ServAttributes.get(x);
if (record.getProduct()) != null) {
Produset.add(record.getProduct());
}
return Produset;
}
private Vector ServAttributes=null;
公共HashSet retProduct(){
HashSet Produset=新HashSet();
对于(int x=0;x
使用像Guava这样的通用帮助程序库,您可以通过一种功能性的方式来实现这一点:
return Sets.newHashSet(Iterables.filter(Iterables.transform(serverAttributes, new Function<ServAttributes, String>() {
public void apply(ServAttributes attributes) {
return attributes.getProduct();
}
}), Predicates.notNull()));
如果您有权访问
ServAttributes
类,则可以覆盖equals
和hashCode
方法,然后使用以下代码删除重复项:
注意:这将返回ServAttributes
的HashSet。如果您只需要产品名称,则必须遍历向量
HashSet<ServAttributes> noDub= new HashSet(new LinkedHashSet(ServAttributes));
请不要使用
向量
:|改用列表
。请遵循此处的命名约定:。尤其是,变量必须以小写字母开头。尤其不要使用与类名称完全相同的变量;这就像是有意使其不可读。不要缩短名称当它损害可读性时(ServAttributes vs ServerAttributes、Produset vs products或productSet).Vector就是List,除非你想推荐其他的List实现,比如ArrayList或LinkedList。这不会跳过null
@BalusC:我不想为他重写他的方法。我向他展示了如何使用增强的for循环。但我会更新番石榴的例子。
HashSet<ServAttributes> noDub= new HashSet(new LinkedHashSet(ServAttributes));
@Override
public int hashCode() {
return product.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if(obj instanceof ServAttributes) {
ServAttributes s1 = (ServAttributes)obj;
if(s1.getProduct().equals(this.getProduct())) {
return true;
}
}
return false;
}