有以下几种方法可以去重一个字符串数组:
- 使用Set:将字符串数组转换为Set集合,由于Set集合不允许重复元素,所以重复的字符串会自动被去除。
String[] array = {"a", "b", "c", "a", "b"}; Setset = new HashSet<>(Arrays.asList(array)); String[] result = set.toArray(new String[set.size()]);
- 使用LinkedHashSet:LinkedHashSet是HashSet的子类,它能够保留元素的插入顺序。可以使用LinkedHashSet来去除重复元素,并保持原有顺序。
String[] array = {"a", "b", "c", "a", "b"}; Setset = new LinkedHashSet<>(Arrays.asList(array)); String[] result = set.toArray(new String[set.size()]);
- 使用Stream API:使用Stream API的distinct()方法对字符串数组进行去重操作。
String[] array = {"a", "b", "c", "a", "b"}; String[] result = Arrays.stream(array).distinct().toArray(String[]::new);
- 使用循环遍历:使用两层循环遍历字符串数组,判断每个元素是否已经存在于结果数组中,如果不存在则将其添加到结果数组中。
String[] array = {"a", "b", "c", "a", "b"}; String[] result = new String[array.length]; int index = 0; for (String s : array) { boolean isDuplicate = false; for (int i = 0; i < index; i++) { if (s.equals(result[i])) { isDuplicate = true; break; } } if (!isDuplicate) { result[index++] = s; } } String[] finalResult = Arrays.copyOf(result, index);