HashSet<String> 筛选出重复的字符串
时间: 2023-05-19 10:05:54 浏览: 82
可以使用 HashSet<String> 和 ArrayList<String> 来实现筛选出重复的字符串。具体实现代码如下:
```java
HashSet<String> set = new HashSet<>();
ArrayList<String> list = new ArrayList<>();
// 假设有一个字符串数组 arr
for (String str : arr) {
if (!set.add(str)) {
list.add(str);
}
}
// list 中即为重复的字符串
```
这段代码的原理是,HashSet 的 add() 方法会返回一个 boolean 值,表示是否添加成功。如果添加不成功,说明这个字符串已经存在于 HashSet 中,即为重复字符串,将其添加到 ArrayList 中即可。
相关问题
使用HashSet<String> 找出重复的字符串
可以使用以下代码来找出重复的字符串:
HashSet<String> set = new HashSet<String>();
HashSet<String> duplicates = new HashSet<String>();
for (String str : strings) {
if (!set.add(str)) {
duplicates.add(str);
}
}
其中,strings 是一个包含多个字符串的数组。首先,我们创建了一个 HashSet 对象 set,用于存储字符串。然后,我们遍历 strings 数组中的每个字符串,如果该字符串已经存在于 set 中,则说明它是一个重复的字符串,我们将其添加到另一个 HashSet 对象 duplicates 中。最后,duplicates 中存储的就是所有重复的字符串。
Map<String,Map<Integer,HashSet<String>>>
这是一个Java中的数据结构,它包含了三个层级:第一层级是一个字符串类型的键,第二层级是一个整数类型的键,第三层级是一个字符串类型的HashSet。可以理解为一个嵌套的字典结构,其中第一层级的字符串是主键,第二层级的整数是次键,第三层级的HashSet则是值的集合。可以通过以下方式访问和操作这个数据结构的元素:
1.获取第一层级的所有键:
```
Set<String> keys1 = map.keySet();
```
2.获取第二层级的所有键:
```
Map<Integer, HashSet<String>> map2 = map.get(key1); // key1为第一层级的某个键
Set<Integer> keys2 = map2.keySet();
```
3.获取第三层级的所有值:
```
HashSet<String> set = map2.get(key2); // key2为第二层级的某个键
```
4.添加元素:
```
if(map.containsKey(key1)){
Map<Integer, HashSet<String>> map2 = map.get(key1);
if(map2.containsKey(key2)){
HashSet<String> set = map2.get(key2);
set.add(value);
}else{
HashSet<String> set = new HashSet<>();
set.add(value);
map2.put(key2, set);
}
}else{
HashSet<String> set = new HashSet<>();
set.add(value);
Map<Integer, HashSet<String>> map2 = new HashMap<>();
map2.put(key2, set);
map.put(key1, map2);
}
```
其中,key1、key2和value均为具体的键和值。