public static void main(String[] args) {
String[] userId = {“1”, “2”, “3”};
String[] userId2 = {“2”, “3”, “4”};
String[] userId3 = {“3”, “5”, “6”};
List uList = new ArrayList<>();
CollUtil.addAll(uList, userId);
CollUtil.addAll(uList, userId2);
CollUtil.addAll(uList, userId3);
String[] res = uList.stream().distinct().toArray(String[]::new);
for (String s : res) {
System.out.println(s);
}
}
以上代码通过使用 CollUtil.addAll() 函数和流式API来将多个字符串数组合并到一个列表中,然后使用 distinct() 函数对列表进行去重操作。输出结果是正确的,但还可以进行以下优化:
使用可变参数,避免使用 CollUtil.addAll() 时需要编写多条语句。
将字符串数组列表增加时的代码抽取到单独的函数中,提高代码的重用性。
简化去重排序的代码。
优化后的Java代码示例如下:
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] userId = {"1", "2", "3"};
String[] userId2 = {"2", "3", "4"};
String[] userId3 = {"3", "5", "6"};
String[] res = distinctAndSort(userId, userId2, userId3);
Arrays.stream(res).forEach(System.out::println);
}
public static String[] distinctAndSort(String[]... arr){
List<String> list = new ArrayList<>();
for (String[] a : arr) {
Collections.addAll(list, a);
}
return list.stream().distinct().sorted().toArray(String[]::new);
}
}
这个优化后的程序使用了可变参数,避免了增加字符串数组列表时需要编写多个 addAll() 的语句。在新函数 distinctAndSort() 中,使用了 Collections.addAll() 函数来将多个字符串数组合并到一个列表中。同时使用 stream()将该列表转换为流,然后调用 distinct() 和 sorted() 进行去重排序,最后将结果转换为字符串数组并返回。
1
2
3
4
5
6
下面给你n个数组,然后去重数字进行排序
首先创建一个空的整数列表 nums,然后遍历每个字符串数组中的每个字符。如果字符是数字,则将其转换为整数并添加到 nums 中,然后用 Collections.sort() 函数对其进行排序,最后输出结果。
import java.util.*;
public class Main {
public static void main(String[] args) {
String[] arr = {"abc12kjh67", "dfg23zlu1", "a38bfg2s", "7sjd93fa8u", "1lakjdhf4"};
List<Integer> nums = new ArrayList<>();
for (String s : arr) {
for (int i = 0; i < s.length(); i++) {
if (Character.isDigit(s.charAt(i))) {
int num = Integer.parseInt("" + s.charAt(i));
if (!nums.contains(num)) {
nums.add(num);
}
}
}
}
Collections.sort(nums);
System.out.println(nums);
}
}
该程序的输出如下
[1, 2, 3, 4, 7, 8, 38, 67, 93]