字符串数组去重java
时间: 2024-06-28 16:00:58 浏览: 6
在Java中,字符串数组去重可以通过多种方法实现,常见的有使用HashSet、HashMap或自定义算法等。以下是几种常见的方法:
1. 使用HashSet(集合去重):
```java
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
String[] array = {"apple", "banana", "apple", "orange", "banana"};
HashSet<String> uniqueStrings = new HashSet<>(Arrays.asList(array));
String[] distinctArray = uniqueStrings.toArray(new String);
System.out.println("Distinct array: " + Arrays.toString(distinctArray));
}
}
```
相关问题
java字符串数组去重代码
可以使用ArrayList来实现Java字符串数组去重。具体代码如下:
```
public String[] removeDuplicates(String[] arr) {
ArrayList<String> list = new ArrayList<>();
for (String str : arr) {
if (!list.contains(str)) {
list.add(str);
}
}
String[] result = new String[list.size()];
result = list.toArray(result);
return result;
}
```
这个方法首先创建了一个ArrayList,然后遍历输入的字符串数组,如果当前字符串不在ArrayList中,就将其添加到ArrayList中。最后,将ArrayList转换为字符串数组并返回。
java 字符串数组去重
你可以使用Set集合来对字符串数组进行去重操作。Set是一种不允许有重复元素的集合,利用这个特性可以很便地去掉重复的字符串。下面是一个示例代码:
```java
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
String[] array = {"apple", "banana", "apple", "orange", "banana"};
Set<String> set = new HashSet<>();
for (String str : array) {
set.add(str);
}
String[] result = set.toArray(new String[0]);
for (String str : result) {
System.out.println(str);
}
}
}
```
在上面的代码中,首先创建了一个HashSet集合对象,然后遍历字符串数组,将每个字符串添加到Set集合中。由于Set不允许有重复元素,所以重复的字符串只会保留一个。最后,通过调用`toArray()`方法将Set集合转换为字符串数组,从而得到去重后的结果。在这个例子中,输出将是:
```
apple
banana
orange
```
这样就完成了字符串数组的去重操作。希望能对你有所帮助!如果还有其他问题,请随时提出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)