JAVA8十大新特性详解(精编)

  作者:记性不好的阁主

转载:https://www.jianshu.com/p/0bf8fe0f153b


List<String> stringCollection = new ArrayList<>();
        stringCollection.add("ddd2");
        stringCollection.add("aaa2");
        stringCollection.add("bbb1");
        stringCollection.add("aaa1");
        stringCollection.add("bbb3");
        stringCollection.add("ccc");
        stringCollection.add("bbb2");
        stringCollection.add("ddd1");

        //截取列表中以a开头的字符串
        stringCollection
                .stream()
                .filter((s) -> s.startsWith("a"))
                .forEach(System.out::println);

        // "aaa2", "aaa1"

        //截取列表中以a开头的字符串并排序
        stringCollection
                .stream()
                .sorted()
                .filter((s) -> s.startsWith("a"))
                .forEach(System.out::println);

        // "aaa1", "aaa2"


        System.out.println(stringCollection);
        // ddd2, aaa2, bbb1, aaa1, bbb3, ccc, bbb2, ddd1


        //将列表中每个字符串的字母变大写,并与a做比较排序
        stringCollection
                .stream()
                .map(String::toUpperCase)
                .sorted((a, b) -> b.compareTo(a))
                .forEach(System.out::println);

        // "DDD2", "DDD1", "CCC", "BBB3", "BBB2", "AAA2", "AAA1"


        //判断列表中任意一个字符串是否以a开头
        boolean anyStartsWithA =
                stringCollection
                        .stream()
                        .anyMatch((s) -> s.startsWith("a"));

        System.out.println(anyStartsWithA);      // true

        //判断列表中所有的字符串是否以a开头
        boolean allStartsWithA =
                stringCollection
                        .stream()
                        .allMatch((s) -> s.startsWith("a"));

        System.out.println(allStartsWithA);      // false

        //判断列表中所有的字符串是否没有以z开头
        boolean noneStartsWithZ =
                stringCollection
                        .stream()
                        .noneMatch((s) -> s.startsWith("z"));

        System.out.println(noneStartsWithZ);      // true


        //截取列表中以b开头的字符串并统计这些字符串的个数
        long startsWithB =
                stringCollection
                        .stream()
                        .filter((s) -> s.startsWith("b"))
                        .count();

        System.out.println(startsWithB);    // 3


        //将列表中每个字符串以#号隔开
        Optional<String> reduced =
                stringCollection
                        .stream()
                        .sorted()
                        .reduce((s1, s2) -> s1 + "#" + s2);

        reduced.ifPresent(System.out::println);
        // "aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2"



        int max = 1000000;
        List<String> values = new ArrayList<>(max);
        for (int i = 0; i < max; i++) {
            UUID uuid = UUID.randomUUID();
            values.add(uuid.toString());
        }


        //串行排序 单线程
        long t0 = System.nanoTime();

        long count = values.stream().sorted().count();
        System.out.println(count);

        long t1 = System.nanoTime();

        long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
        System.out.println(String.format("sequential sort took: %d ms", millis));

        //并行排序 多线程
        t0 = System.nanoTime();

        count = values.parallelStream().sorted().count();
        System.out.println(count);

        t1 = System.nanoTime();

        millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0);
        System.out.println(String.format("parallel sort took: %d ms", millis));


        //遍历map中的k-v对
        Map<Integer, String> map = new HashMap<>();

        for (int i = 0; i < 10; i++) {
            map.putIfAbsent(i, "val" + i);
        }

        map.forEach((id, val) -> System.out.println(val));

        //map的其他函数
        map.computeIfPresent(3, (num, val) -> val + num);
        map.get(3);             // val33

        map.computeIfPresent(9, (num, val) -> null);
        map.containsKey(9);     // false

        map.computeIfAbsent(23, num -> "val" + num);
        map.containsKey(23);    // true

        map.computeIfAbsent(3, num -> "bam");
        map.get(3);             // val33


        //删除map中 key=3 value=val3 的键值对
        map.remove(3, "val3");
        map.get(3);             // val33

        //删除map中 key=3 value=val33 的键值对
        map.remove(3, "val33");
        map.get(3);             // null


        //尝试根据key获取map中的value,若没有则返回not found
        map.getOrDefault(42, "not found");  // not found


        //map合并
        map.merge(9, "val9", (value, newValue) -> value.concat(newValue));
        map.get(9);             // val9

        map.merge(9, "concat", (value, newValue) -> value.concat(newValue));
        map.get(9);             // val9concat


        //更多详细参照:https://www.jianshu.com/p/0bf8fe0f153b



常用流转换示例

package com.xrosstools.xdecision.sample;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author xushunjie
 * @date 2021/12/7 14:11
 */

public class test4 {


    public static void main(String[] args) throws Exception {

        List<Person> personList = new ArrayList<>();
        Person person1 = new Person();
        person1.setId(1);
        person1.setName("小明");
        person1.setAge(25);
        Person person2 = new Person();
        person2.setId(2);
        person2.setName("小张");
        person2.setAge(26);
        Person person3 = new Person();
        person3.setId(3);
        person3.setName("小李");
        person3.setAge(26);
        personList.add(person1);
        personList.add(person2);
        personList.add(person3);
        List<Integer> personIdList = personList.stream().map(Person::getId).collect(Collectors.toList());
        System.out.println(personIdList);
        // [1, 2, 3]

        personIdList = personList.stream().map(Person::getId).filter(id -> id >1).collect(Collectors.toList());
        System.out.println(personIdList);
        // [2, 3]

        List<String> personNameList = personList.stream().map(Person::getName).collect(Collectors.toList());
        String names = personNameList.stream().collect(Collectors.joining(","));
        System.out.println(names);
        // 小明,小张,小李

        Map<Integer, String> map = personList.stream().collect(Collectors
                .toMap(Person::getId, Person::getName));
        System.out.println(map);
        // {1=小明, 2=小张, 3=小李}

        Map<Integer, Person> personMap = personList.stream().collect(Collectors
                .toMap(Person::getId, Function.identity()));
        System.out.println(personMap);
        // {1=Person{id=1, name='小明', age=25}, 2=Person{id=2, name='小张', age=26}, 3=Person{id=3, name='小李', age=26}}

        Map<Integer, List<Person>> stringListMap =
                personList.stream().collect(Collectors.groupingBy(Person::getAge));
        System.out.println(stringListMap);
        // {25=[Person{id=1, name='小明', age=25}], 26=[Person{id=2, name='小张', age=26}, Person{id=3, name='小李', age=26}]}

        List<Person> nonMatch = personList.stream().filter(person -> personList.stream().map(Person::getAge).noneMatch(age -> person.getAge() == 26)).collect(Collectors.toList());
        System.out.println(nonMatch);
        // [Person{id=1, name='小明', age=25}]

        List<Person> anyMatch = personList.stream().filter(person -> personList.stream().map(Person::getAge).anyMatch(age -> person.getAge() == 26)).collect(Collectors.toList());
        System.out.println(anyMatch);
        // [Person{id=2, name='小张', age=26}, Person{id=3, name='小李', age=26}]

    }






}

class Person {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}


// 综合应用

// pojos 全部数据 (带id)
// updatePojoList 需要更新的数据 (带id)
// deletePojoList 需要删除的数据 (带id)
// 从pojos中剔除updatePojoList中的数据,剩下的数据为需要删除的数据deletePojoList

List<Pojo> deletePojoList = pojos.stream().filter(Pojo -> updatePojoList.stream().map(Pojo::getId).noneMatch(pojoId -> Objects.equals(Pojo.getId(), pojoId))).collect(Collectors.toList());



java steam对象根据属性值排序 正序 倒序


参考:https://blog.csdn.net/qq_15058425/article/details/107019176


public class SortTest {
    public static void main(String[] args) {
        User user1=new User("1111",20);
        User user2=new User("2222",19);
        User user3=new User("3333",21);

        List<User> list=new ArrayList<>();
        list.add(user1);
        list.add(user2);
        list.add(user3);

        list = list.stream().sorted(Comparator.comparing(User::getAge)).collect(Collectors.toList());
        System.out.println("根据年龄顺序:==="+list);

        list = list.stream().sorted(Comparator.comparing(User::getAge,Comparator.reverseOrder())).collect(Collectors.toList());
        System.out.println("根据年龄倒序:==="+list);
    }
}

排序判空并倒序


generalNurseCountOut.sort(Comparator.comparing(PerformanceAppraisalRespDTO::getNurseLevel, Comparator.nullsFirst(String::compareTo)).reversed());


java steam对象根据属性值去重


List<User> distinctList = list.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toMap(User::getUserCode, Function.identity(), (existing, replacement) -> existing),
                        map -> new ArrayList<>(map.values())
                ));

stream操作嵌套列表


List<Long> scheduleIdList = userShowDetailRespDTOList.stream()
        .filter(u -> ListUtils.isNotEmpty(u.getDateDetailList()))
        .map(ScheduleUserShowDetailRespDTO::getDateDetailList)
        .flatMap(Collection::stream)
        .filter(d -> ListUtils.isNotEmpty(d.getScheduleList()))
        .map(ScheduleUserDateDetailRespDTO::getScheduleList)
        .flatMap(Collection::stream)
        .map(ScheduleUserDetailRespDTO::getScheduleId)
        .distinct().collect(toList());

java stream groupingBy分组后再进行列表排序


Map<String, List<ScheduleUserDetailDO>> scheduleUserDetailMap = scheduleUserDetailDOList.stream().collect(groupingBy(ScheduleUserDetailDO::getUserId,
                    collectingAndThen(toList(), t -> t.stream().sorted(
                            Comparator.comparing(ScheduleUserDetailDO::getCreateTime)
                                    .thenComparing(ScheduleUserDetailDO::getSortVal)
                    ).collect(toList()))));

java stream groupingBy分组后不改变列表顺序


Map<String, List<QCIndexDataRespDTO>> groupMap = qcIndexDataRespDTOList.stream()
.collect(Collectors.groupingBy(s -> s.getUnitId() + "|" + s.getQcIndexDictId() + "|" + s.getQcIndexTargetValue() + "|" + s.getQcIndexLevel(), LinkedHashMap::new, Collectors.toList()));


java stream 动态指定多个字段排序


int sortIndex = 0;
Comparator<ReportTableBody> comparator = null;
for (String orderExpr : globalOrderList) {
String columnId = orderExpr.split("-")[0];
String order = orderExpr.split("-")[1];
if (OrderByEnum.DESC.name().equals(order)) {
if (sortIndex == 0) {
comparator = Comparator.comparing(reportTableBody ->
reportTableBody.getColumnValueList().stream().filter(reportTableColumnValue -> StringUtil.equals(columnId, reportTableColumnValue.getColumnId()))
.findFirst().get().getValue(), Comparator.reverseOrder());
} else {
comparator = comparator.thenComparing(reportTableBody ->
reportTableBody.getColumnValueList().stream().filter(reportTableColumnValue -> StringUtil.equals(columnId, reportTableColumnValue.getColumnId()))
.findFirst().get().getValue(), Comparator.reverseOrder());
}
} else {
if (sortIndex == 0) {
comparator = Comparator.comparing(reportTableBody ->
reportTableBody.getColumnValueList().stream().filter(reportTableColumnValue -> StringUtil.equals(columnId, reportTableColumnValue.getColumnId()))
.findFirst().get().getValue());
} else {
comparator = comparator.thenComparing(reportTableBody ->
reportTableBody.getColumnValueList().stream().filter(reportTableColumnValue -> StringUtil.equals(columnId, reportTableColumnValue.getColumnId()))
.findFirst().get().getValue());
}
}
sortIndex++;
}
if (comparator != null) {
reportTableBodyList = reportTableBodyList.stream().sorted(comparator).collect(Collectors.toList());
}



相关推荐

分类选择