JDK8使用Stream对数组合并、去重

传统的写法

String[] str1 = {"08:00", "09:00", "10:00", "18:00", "21:00"};
String[] str2 = {"12:00", "09:00", "10:00", "11:00"};

 //合并不去重
 List<String> list1 = new ArrayList<String>(Arrays.asList(str1));
 list1.addAll(Arrays.asList(str2));
 String[] str3 = (String[])list1.toArray(new String[list1.size()]);

 //利用set特性合并去重
 Set set = new HashSet<String>(Arrays.asList(str1));
 set.addAll(new HashSet<String>(Arrays.asList(str2)));
 str3 = (String[])set.toArray(new String[set.size()]);

jdk8写法

String[] str1 = {"08:00", "09:00", "10:00", "18:00", "21:00"};
String[] str2 = {"12:00", "09:00", "10:00", "11:00"};

//jdk8 stream
str3 = Stream.concat(Stream.of(str1), Stream.of(str2)) //合并
        .distinct()     //去重
        .sorted()       //排序
        .peek(System.out:println)
        .toArray(String[]::new);

额外记录reduce用法

String[] temp = Stream.concat(Stream.of(str1), Stream.of(str2)) //合并
       .distinct()     //去重
        .sorted()       //排序
        .reduce((a, b) -> {     //拼接
            a = a + "-" + b + "," + b;
            return a;
        }).get().toString().split(",");

//去掉垃圾数据
str3 = Arrays.asList(temp)
        .stream()
        .filter(v -> v.contains("-"))
        .peek(System.out::println)
        .toArray(String[]::new);

输出

08:00-09:00
09:00-10:00
10:00-11:00
11:00-12:00
12:00-18:00
18:00-21:00

猜你喜欢

转载自blog.csdn.net/ragin/article/details/78226034