java8写法总结

一直看别人再写java8的语法 自己总结写

Map

开始 idea 格式化代码 ctrl + alt + L

1.输出key和value (常用)

        Map<String, Object> map = new HashMap<>();
        for (int i = 1; i < 100; ++i) {
            map.put(String.valueOf(i), i);
        }
        map.forEach((k, v) -> {
            System.out.println("key:value = " + k + ":" + v);
        });

复制代码

2.通过Map.entrySet遍历key和value,在大容量时推荐使用

        Map<String, Object> map = new HashMap<>(100000);
        for (int i = 1; i < 100000; ++i) {
            map.put(String.valueOf(i), i);
        }
        //java8 之前  遍历完花费总时间为:1077
         for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue());
        }
        //java8  遍历完花费总时间为:493
        map.entrySet().forEach(entry -> System.out.println("key:value = " + entry.getKey() + ":" + entry.getValue()));
复制代码

3.替换Map中所有Entry的value值,这个值由旧的key和value计算得出

在Java 8中的Map接口增加了一些default方法,提升了对key, value操作的便利性

        Map<Integer, String> map = new HashMap<>();
        map.put(1, "a");
        map.put(2, "b");
        map.put(3, "c");

       map.replaceAll((k,v)->(k+1)+v);
       map.forEach((k,v)-> System.out.println(k+" "+v));
        // 输出
        //        1 2a
        //        2 3b
        //        3 4c
       
复制代码

4.remove 方法

接收2个参数,key和value,如果key关联的value值与指定的value值相等(equals),则删除这个元素

// 删除成功,输出 null
System.out.println(map.get(2))
复制代码

5.replace(K key, V oldValue, V newValue) 方法

map.replace(1, "a", "z");
// 替换成功, 输出 z
System.out.println(map.get(1));
复制代码

6.compute 方法 根据key 变化值 改变原来map的值

compute方法是computeIfAbsent与computeIfPresent的综合体
快速修改指定map的值

map.computeIfPresent(1, (key, value) -> (key + 1) + value);
// 存在key为1, 则根据旧的key和value计算新的值,输出 2a
System.out.println(map.get(1));

map.computeIfPresent(2, (key, value) -> null);
// 存在key为2, 根据旧的key和value计算得到null,删除该值,输出 null
System.out.println(map.get(2));
复制代码

List

开始 go

1.遍历

        Person p2 = new Person("李四", 20);
        Person p3 = new Person("王五", 26);
        List<Person> personList = new ArrayList<Person>();
        personList.add(p1);
        personList.add(p2);
        personList.add(p3);
        personList.forEach(p -> System.out.println(p.getAge()));
复制代码

2.从 List 中取出某个属性的组成 list 集合

        List<String> stIdList1 = personList.stream().map(Person::getName).collect(Collectors.toList());
        stIdList1.forEach(s->{
            System.out.println(s);
        });
复制代码

3.从 List 中取出某个属性的组成 list 集合 (去重)

        List<String> stringList = personList.stream().map(Person::getName).distinct().collect(Collectors.toList());
        System.out.println(stringList);
复制代码

4.filter()过滤列表

        List<Person> filterList = personList.stream().filter(p -> p.getAge().equals(1)).collect(Collectors.toList());
        System.out.println(filterList);
复制代码

5. 去除List中重复的对象 (一个属性)

               // 根据name去重
        List<Person> unique = personList.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new)
        );
        System.out.println(unique);
复制代码

6. 根据name,sex两个属性去重 (多个属性)

        List<Person> unique = personList.stream().collect(
                Collectors. collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getAge()))), ArrayList::new)
        );
        System.out.println(unique);
复制代码

7. List转Map

       Map<String, String> collect = personList.stream().collect(Collectors.toMap(p -> p.getName(), p -> p.getName()));
        System.out.println(collect);
复制代码

8. 利用stream().map()对List进行大写处理,并给另外一个List赋值,并对其遍历

        List<String> list4 = new ArrayList<String>();
        list4 = list.stream().map(item->item.toUpperCase()).collect(Collectors.toList());
复制代码

9. 求某一个数列的最大值、最小值、和、平均值、数列元素数

                  List<Integer> listint = new ArrayList<Integer>();
			listint.add(1);
			listint.add(2);
			listint.add(3);
			listint.add(4);
			listint.add(5);
			IntSummaryStatistics stat = listint.stream().mapToInt((item)->item).summaryStatistics();
			System.out.println("max:"+stat.getMax());
			System.out.println("min:"+stat.getMin());
			System.out.println("sum:"+stat.getSum());
			System.out.println("count:"+stat.getCount());
			System.out.println("average:"+stat.getAverage());
 
复制代码

10.常用例子

   OptionalInt result = Arrays.stream(array).parallel()
                .filter(i->i>20) // 过滤,条件是大于20
                .map(i->i*i)  // 映射,得到数组中每个数的平方
                .sorted()   // 排序
                .distinct()   // 去掉重复元素
                .limit(10)   // 取其中前10个元素
                .max();    // 求出当前数组的最大值
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享