Collections工具类和Stream流

1. Collections工具类

  • Collections是一个集合操作的工具类,它里面包含的方法有:
    ① 批量添加:例如Collections.addAll(list,"A","B","C");
    ② 翻转:例如Collections.reverse(list);
    ③ 填充:例如Collections.fill(list, "--");
package com.xxx;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class TestCollections {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        //批量添加
        Collections.addAll(list, "Java", "C++", "PHP");
        System.out.println(list);
        //反转
        Collections.reverse(list);
        System.out.println(list);
        //填充
        Collections.fill(list, "--");
        System.out.println(list);
        //空集合
        List<String> list1 = Collections.emptyList();
        System.out.println(list1.size());//0
        //UnsupportedOperationException
        //list1.add("Java");
        System.out.println(list1);

    }
}

在这里插入图片描述

package com.xxx;

import java.util.*;

public class TestCollections {

    public static void main(String[] args) {

        //线程不安全的
        //synchronizedList
        List<String> list1 = new ArrayList<>();
        List<String> list2 = Collections.synchronizedList(list1);
        System.out.println(list2.getClass().getName());

        //SynchronizedMap
        Map<String, String> map = Collections.synchronizedMap(new HashMap<>());
        System.out.println(map.getClass().getName());
    }
}

在这里插入图片描述

  • 还有一些其他方法:
    ① 排序:sort()
    ② 乱序:shuffle()
package com.xxx;

import java.util.*;

public class TestCollections {

    public static void main(String[] args) {

        List<Integer> list = new ArrayList<>();
        Collections.addAll(list, 1, 2, 4, 6, 0, 5);
        System.out.println(list);
        Collections.sort(list);
        System.out.println(list);
        Collections.shuffle(list);
        System.out.println(list);
        Collections.shuffle(list);
        System.out.println(list);
    }
}

在这里插入图片描述

2. Stream流

JDK1.8发行的时候实际上是世界上大数据兴起的时候,在整个大数据的开发里面有一个最经典的模型:MapReduce模型。Map用于处理数据,而Reduce则是为了分析数据

而在Java类集中,由于其本身的作用就可以进行大量数据的存储,所以就顺其自然得产生了MapReduce操作,而这些操作可以通过Stream数据流来完成。

2.1 Collection的改进

JDK1.8开始,Collection接口里面除了定义一些抽象方法外,也提供了一些普通方法,比如:
① forEach()输出支持:default void forEach(Consumer<? super T> action)
② 取得Stream数据流对象:default Stream stream()

package com.xxx;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Stream;

public class TestStream {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        Collections.addAll(list, "Java", "C++", "PHP");
        //函数式编程
        list.forEach(s -> System.out.println(s));
        //方法引用
        list.forEach(System.out::println);

        System.out.println("----------");

        //实例化Stream对象
        Stream<String> stream = list.stream();
        System.out.println(stream.count());

    }
}

在这里插入图片描述

2.2 Stream操作

① 过滤:filter
② 收集器:collect,希望在数据过滤后得到具体数据
③ 跳过多少个元素:skip
④ 设置取出最大内容:limit

package com.xxx;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TestStream {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>();
        Collections.addAll(list, "Java", "C++", "PHP", "JavaScript", "C", "PHP", "Python");

        //过滤输出元素中包含Java或者C的元素
        List<String> newList1 = list.stream()
                .filter(s -> {
                    return s.contains("Java") || s.contains("C");
                })
               .collect(Collectors.toList());
                //收集完的数据依然属于List集合,所以可以直接使用List进行接收
        System.out.println(newList1);

        //跳过多少个元素取出多少个元素(分页处理)
        List<String> newList2 = list.stream()
                .skip(2)
                .limit(3) //3
                .skip(1) //2
                .limit(3)
                .collect(Collectors.toList());
        System.out.println(newList2);

        //综合操作
        List<String> newList3 = list.stream()
                .skip(2)
                .limit(5)
                .filter(s -> s.contains("P"))
                .collect(Collectors.toList());
        System.out.println(newList3);


    }
}

在这里插入图片描述

2.3 MapReduce模型

MapReduce是整个Stream流的核心所在。由以下两个阶段所组成:
map():指的是针对于数据进行先期的操作处理
reduce():进行数据的统计分析

package com.xxx;

import java.util.ArrayList;
import java.util.List;

class Order {

    private String title;
    private double price;
    private int amount;

    public Order(String title, double price, int amount) {
        this.title = title;
        this.price = price;
        this.amount = amount;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }
}

public class TestMapReduce {

    public static void main(String[] args) {

        //在List集合中保存这些订单的信息
        List<Order> orderList = new ArrayList<>();
        orderList.add(new Order("Iphone", 8999.99, 10));
        orderList.add(new Order("外星人笔记本", 12999.99, 5));
        orderList.add(new Order("MacBookPro", 18999.99, 5));
        orderList.add(new Order("Java从入门到放弃.txt", 9.99, 20000));
        orderList.add(new Order("中性笔", 1.99, 200000));

        //计算订单金额总和
        double totalPrice = orderList.stream()
                //结果应该为double类型
                //.map(order -> order.getAmount() * order.getPrice())
                .mapToDouble(order -> order.getPrice() * order.getAmount())
                .reduce((sum, x) -> sum = sum + x)
                .orElseGet(() -> 0.0D);
        System.out.println("订单总额为:"+totalPrice);

    }
}

在这里插入图片描述

  • MapReduce做统计分析(最大最小值、平均值、总量等):
package com.xxx;

import java.util.ArrayList;
import java.util.DoubleSummaryStatistics;
import java.util.List;

class Order {

    private String title;
    private double price;
    private int amount;

    public Order(String title, double price, int amount) {
        this.title = title;
        this.price = price;
        this.amount = amount;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }
}

public class TestMapReduce {

    public static void main(String[] args) {

        //统计分析(订单数量、最大金额、最小金额、平均金额、订单总金额)
        List<Order> orderList = new ArrayList<>();
        orderList.add(new Order("Iphone", 8999.99, 10));
        orderList.add(new Order("外星人笔记本", 12999.99, 5));
        orderList.add(new Order("MacBookPro", 18999.99, 5));
        orderList.add(new Order("Java从入门到放弃.txt", 9.99, 20000));
        orderList.add(new Order("中性笔", 1.99, 200000));

        //第一种方法:
        int orderCount = 0;
        double maxPrice = Double.MIN_VALUE;
        double minPrice = Double.MAX_VALUE;
        double orderAvg = 0.0D;
        double orderTotal = 0.0D;

        for(Order order : orderList) {
            orderCount++;
            double orderPrice = order.getPrice() * order.getAmount();
            if (maxPrice < orderPrice) {
                maxPrice = orderPrice;
            }
            if (minPrice > orderPrice) {
                minPrice = orderPrice;
            }
            orderTotal = orderTotal + orderPrice;
        }
        orderAvg = orderTotal / orderCount;

        System.out.println("订单数量:" + orderCount);
        System.out.println("最大金额:" + maxPrice);
        System.out.println("最小金额:" + minPrice);
        System.out.println("平均金额:" + orderAvg);
        System.out.println("订单总金额:" + orderTotal);

        System.out.println("---------------");

        //第二种方法:
        DoubleSummaryStatistics statistics = orderList.stream()
                .mapToDouble(order -> order.getAmount() * order.getPrice())
                .summaryStatistics();

        System.out.println("订单数量:" + statistics.getCount());
        System.out.println("最大金额:" + statistics.getMax());
        System.out.println("最小金额:" + statistics.getMin());
        System.out.println("平均金额:" + statistics.getAverage());
        System.out.println("订单总金额:" + statistics.getSum());

    }
}

在这里插入图片描述

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值