8的Stream

1、stream排序

Java8排序stream.sorted()

package com.stream.demo;
 
public class Student implements Comparable<Student> {
	private int id;
	private String name;
	private int age;
 
	public Student(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
 
	public int getId() {
		return id;
	}
 
	public String getName() {
		return name;
	}
 
	public int getAge() {
		return age;
	}
 
	@Override
	public int compareTo(Student ob) {
		return name.compareTo(ob.getName());
	}
 

 

}

使用

package com.stream.demo;
 
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
 
public class StreamListDemo {
	public static void main(String[] args) {
		List<Student> list = new ArrayList<>();
		list.add(new Student(1, "Mahesh", 12));
		list.add(new Student(2, "Suresh", 15));
		list.add(new Student(3, "Nilesh", 10));
 
//==================================================================
		List<Student> slist = list.stream().sorted().collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
//==================================================================
		slist = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 //========================================================================================
		//		或者这种写法	.sorted((u1,u2)->{return u2.getxxx().compareTo(u1.getxxx()); })   
		slist = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
 
//==================================================================
		slist = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
		slist.forEach(e -> System.out.println("Id:" + e.getId() + ", Name: " + e.getName() + ", Age:" + e.getAge()));
//==================================================================
		//多字段排序
		// 先以属性一升序,升序结果进行属性一降序,再进行属性二升序,结果进行属性一降序属性二降序
		list.stream().sorted(Comparator.comparing(::属性一).reversed().thenComparing(::属性二).reversed());

	}
}

2、stream去重

一、使用distinct()多字段去重

distinct() 根据hashCode() 作为去重的 可以重写hashCode方法

//重写实体Person 
 @Override
    public int hashCode() {
        return Objects.hash(getName(), getAge());
    }
        Person person1 = new Person();
        person1.setAge(18);
        person1.setName("18");
 
        Person person2 = new Person();
        person2.setAge(19);
        person2.setName("19");
 
        Person person3 = new Person();
        person3.setAge(19);
        person3.setName("19");
 
        List<Person> people = new ArrayList<>();
        people.add(person1);
        people.add(person2);
        people.add(person3);

        List<Person> collect1 = people.stream().distinct().collect(Collectors.toList());

二、使用stream多字段无需重写hashcode方法

// 根据id去重
list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                new TreeSet<>(Comparator.comparing(Person::getPackId))),ArrayList::new));


// 根据id和ctn去重
list = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                new TreeSet<>(Comparator.comparing(t -> t.getPackId() + "#" + t.getActCtn()))),ArrayList::new));

当使用多个字段进行去重时,中间用 “#” 连接即可

3、转map


public class DemoListToMap {
    List<Student> list = Arrays.asList(new Student(1, 18, "阿龙", GenderColumn.BOY.getCode()),
                                       new Student(2, 17, "小花", GenderColumn.GIRL.getCode()),
                                       new Student(3, 17, "阿浪", GenderColumn.LADYBOY.getCode()));
    @Test
    public void listToMapByObjectValue(){
        // value 为对象  Function.identity()代替student -> student
        Map<Integer, Student> map = list.stream().collect(Collectors.toMap(Student::getId, student -> student));
        // 遍历打印结果
        map.forEach((key, value) -> {
            System.out.println("key: " + key + "    value: " + value);
        });
    }
}

出现相同的话会报错 解决方法

@Test
    public void listToMapByAgeKey(){
        // value 为对象中的属性
        Map<Integer, String> map = list.stream().collect(
        									//舍相同的key2
            Collectors.toMap(Student::getAge, Student::getName, (key1, key2) -> key1)
        );
        map.forEach((key, value) -> {
            System.out.println("key: " + key + "    value: " + value);
        });
    }

4、分组

Map<String, List<Employee>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity));
 map.forEach((key,val)->{
            System.out.println("城市:"+key+" ---员工集: "+val);
});
    /**
     * 城市:广州 ---员工集: [Employee{name='1', city='广州', sales=100}, Employee{name='5', city='广州', sales=20}, Employee{name='6', city='广州', sales=30}, Employee{name='8', city='广州', sales=30}]
     * 城市:上海 ---员工集: [Employee{name='0', city='上海', sales=30}]
     * 城市:杭州 ---员工集: [Employee{name='2', city='杭州', sales=50}, Employee{name='7', city='杭州', sales=30}]
     * 城市:北京 ---员工集: [Employee{name='3', city='北京', sales=30}, Employee{name='4', city='北京', sales=50}, Employee{name='9', city='北京', sales=30}]
     */

计算分组总额

  Map<String, Integer> map = emps.stream().
                collect(Collectors.groupingBy(Employee::getCity, Collectors.summingInt(Employee::getSales)));
        //                                    先按city分组                                  再对组里面的成员,统计总销售额
        map.forEach((key,val)->{
            System.out.println("城市:"+key+" 销售总额:"+val);
        });
    /**
     * 城市:广州 销售总额:120
     * 城市:上海 销售总额:50
     * 城市:杭州 销售总额:180
     * 城市:北京 销售总额:50
     */

查看分组去重分组用户名字

       List<Employee> emps = getEmps();
        Map<String, Set<String>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity, Collectors.mapping(Employee::getName, Collectors.toSet())));
        map.forEach((key,val)->{
            System.out.println(""+key+" ---人员姓名: "+val);
        });

计算分组中最大值


        Map<String, Employee> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity,
                Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingInt(Employee::getSales)), Optional::get)));

        map.forEach((key,val)->{
            System.out.println("城市:"+key+" 销售额最大员工:"+val);
        });

分组名字排序 并去重分组重复

       TreeMap<String, Set<String>> map = emps.stream().collect(Collectors.groupingBy(Employee::getCity, TreeMap::new, Collectors.mapping(Employee::getName, Collectors.toSet())));
        map.forEach((key,val)->{
            System.out.println("城市:"+key+" 姓氏集:"+val);
        });

分组后做额外的指定的形式进行返回 返回类型随意

        Integer collect = users.stream().filter(u -> true).collect(Collectors.collectingAndThen(Collectors.groupingBy(User::getId), map -> {
            Integer integer1 = null;
            for (Integer integer : map.keySet()) {
                integer1 = map.get(integer).stream().map(User::getId).reduce(Integer::sum).get();
            }
            return integer1;
        }));

5、anyMatch / allMatch / noneMatch匹配用法

anyMatch:判断的条件里,任意一个元素成功,返回true
allMatch:判断条件里的元素,所有的都是,返回true
noneMatch:与allMatch相反,判断条件里的元素,所有的都不是,返回true


    List<Integer> list = Arrays.asList(1, 2, 1, 1, 1);
    
    boolean anyMatch = list.stream().anyMatch(f -> f == (1));
    boolean allMatch = list.stream().allMatch(f -> f == (1));
    boolean noneMatch = list.stream().noneMatch(f -> f == (1));

6、交集、并集、差集、去重并集

表达式可以使用 代替 、、、、集合::方法

//List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
List<String> reduce2 = list2.stream().filter(list1::contains).collect(Collectors.toList());
 public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("1");
        list1.add("2");
        list1.add("3");
        list1.add("5");
        list1.add("6");
 
        List<String> list2 = new ArrayList<String>();
        list2.add("2");
        list2.add("3");
        list2.add("7");
        list2.add("8");
 
        // 交集
        List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
        System.out.println("---交集 intersection---");
        intersection.parallelStream().forEach(System.out :: println);
 
        // 差集 (list1 - list2)
        List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
        System.out.println("---差集 reduce1 (list1 - list2)---");
        reduce1.parallelStream().forEach(System.out :: println);
 
        // 差集 (list2 - list1)
        List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
        System.out.println("---差集 reduce2 (list2 - list1)---");
        reduce2.parallelStream().forEach(System.out :: println);
 
        // 并集
        List<String> listAll = list1.parallelStream().collect(Collectors.toList());
        List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
        listAll.addAll(listAll2);
        System.out.println("---并集 listAll---");
        listAll.parallelStream().forEachOrdered(System.out :: println);
 
        // 去重并集
        List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());
        System.out.println("---得到去重并集 listAllDistinct---");
        listAllDistinct.parallelStream().forEachOrdered(System.out :: println);
 
        System.out.println("---原来的List1---");
        list1.parallelStream().forEachOrdered(System.out :: println);
        System.out.println("---原来的List2---");
        list2.parallelStream().forEachOrdered(System.out :: println);
 
    }


7、map分组后排序

HashMap<Integer, Integer> map = new HashMap<>();
//根据key排序
map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toList());
//根据key倒叙
map.entrySet().stream().sorted(Collections.reverseOrder(Map.Entry.comparingByKey())).collect(Collectors.toList());
//  tree   
		TreeMap<Integer, User> integerObjectTreeMap = new TreeMap<>((o1, o2) -> o1-o1);
        integerObjectTreeMap.putAll(map);
//tree   倒叙
		 TreeMap<Integer, User> integerObjectTreeMap = new TreeMap<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }
        }.reversed());

8、单个字段的求和

//第一种方式
int suma = list.stream().map(e -> e.getAge()).reduce(Integer::sum).get();//求和

int maxa = list.stream().map(e -> e.getAge()).reduce(Integer::max).get();//最大

int mina = list.stream().map(e -> e.getAge()).reduce(Integer::min).get();//最小


//第二种方式

double doublesum = list.stream().mapToDouble(Student::getAge).sum();//和

int intmax = list.stream().mapToInt(Student::getAge).max().getAsInt();//最大

int intmin = list.stream().mapToInt(Student::getAge).min().getAsInt();//最小

double avg = list.stream().mapToDouble(Student::getAge).average().getAsDouble();//平均

9、集合中对象得数组获取

//getCartInfo获取得是数组
        List<YxStoreCartQueryVo> cartQueryVos = confirmOrderVos.stream()
                .map(ConfirmOrderVo::getCartInfo)
                .flatMap(List::stream)
                .collect(Collectors.toList());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java 8引入了Stream API,它是一种处理集合数据的新方式。Stream API提供了一种流式操作的方式,可以对集合进行过滤、映射、排序、聚合等操作,使得代码更加简洁、易读和高效。 Stream是一个来自数据源的元素队列并支持聚合操作。它可以是集合、数组、I/O channel、产生器等。Stream操作可以顺序执行,也可以并行执行。 Java 8 Stream API的特点包括: 1. 延迟执行:Stream操作通常是延迟执行的,只有在终止操作时才会触发实际的计算。 2. 内部迭代:Stream API使用内部迭代的方式,不需要显式地编写循环,使得代码更加简洁。 3. 函数式编程:Stream API支持函数式编程风格,可以通过Lambda表达式来定义操作。 4. 并行处理:Stream API提供了并行处理的能力,可以充分利用多核处理器的优势,提高处理速度。 使用Stream API可以通过一系列的中间操作和终止操作来对集合进行处理。中间操作包括过滤、映射、排序等操作,终止操作包括聚合、收集、遍历等操作。 下面是一些常用的Stream操作方法: 1. filter(Predicate<T> predicate):根据指定条件过滤元素。 2. map(Function<T, R> mapper):将元素进行映射转换。 3. sorted(Comparator<T> comparator):对元素进行排序。 4. distinct():去除重复的元素。 5. limit(long maxSize):限制元素的数量。 6. skip(long n):跳过指定数量的元素。 7. forEach(Consumer<T> action):对每个元素执行指定操作。 8. collect(Collector<T, A, R> collector):将元素收集到集合中。 9. reduce(BinaryOperator<T> accumulator):对元素进行归约操作。 10. parallel():启用并行处理。 以上只是Stream API的一部分常用操作,还有更多的操作方法可以根据具体需求使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张航柯

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值