java后台合并数组并去重

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]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值