java hashset去重复
时间: 2023-11-12 13:49:43 浏览: 84
Java HashSet可以用于去除重复元素。要使用HashSet去除重复元素,可以将数组转换为HashSet。根据提供的代码段,可以使用以下方法之一去除重复元素:
方法一(保持原有顺序):
```java
String[] arr = new String[] {"java", "265", "com", "very", "good", "web"};
Set<String> noDups = new LinkedHashSet<String>(Arrays.asList(arr));
System.out.println("(LinkedHashSet) distinct words: " + noDups);
```
方法二(顺序打乱):
```java
String[] arr = new String[] {"java", "265", "com", "very", "good", "web"};
Set<String> noDups = new HashSet<String>(Arrays.asList(arr));
System.out.println("(HashSet) distinct words: " + noDups);
```
方法三(顺序打乱):
```java
String[] arr = new String[] {"java", "265", "com", "very", "good", "web"};
Set<String> s = new HashSet<String>();
for (String a : arr) {
if (!s.add(a)) {
System.out.println("Duplicate detected: " + a);
}
}
System.out.println(s.size() + " distinct words: " + s);
```
以上三种方法都可以用于去重,但根据具体需求选择相应的方法。
阅读全文