java 字符串数组去重
时间: 2023-10-04 08:04:10 浏览: 75
你可以使用 Set 数据结构来去除 Java 字符串数组中的重复元素。Set 是一个不允许重复元素的集合,可以方便地去除重复项。以下是一个示例代码:
```java
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
String[] array = {"apple", "banana", "orange", "apple", "kiwi", "banana"};
// 将数组转换为 Set
Set<String> set = new HashSet<>(Arrays.asList(array));
// 转换回数组
String[] result = set.toArray(new String[0]);
// 输出结果
System.out.println(Arrays.toString(result));
}
}
```
运行以上代码,输出结果为:`[banana, orange, apple, kiwi]`。通过转换为 Set,重复的元素被去除了。然后再将 Set 转换回数组即可得到去重后的结果。
相关问题
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
```
这样就完成了字符串数组的去重操作。希望能对你有所帮助!如果还有其他问题,请随时提出。
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转换为字符串数组并返回。
相关推荐
![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_column_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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)