JDK8后新特性笔记

1.List<对象> 排序

简单写法

import java.util.stream.Collectors;

// 使用 Stream 排序 ,其中有需要的话 MaterialDictionaryResponeseExcelDTO::getConfig).reversed() 表示倒序的意思,如果不使用此方法则是正序
			List<MaterialDictionaryResponeseExcelDTO> excelListData = list.stream()
					.sorted(Comparator.comparing(MaterialDictionaryResponeseExcelDTO::getConfig).reversed())
	                .collect(Collectors.toList());
以前的写法
// 使用 Comparable 自定的规则进行排序
        Collections.sort(list);
        

在对象中实现Comparable<>接口

@Data
class Person implements Comparable<Person> {
    private int id;
    private int age;
    private String name;
 
    public Person(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }
    @Override
    public int compareTo(Person p) {
        return p.getAge() - this.getAge();
    }
}

2.List<> 循环

import java.util.stream.Collectors;
没有返回值

list.forEach(p -> {
            System.out.println(p);
        });

有返回值

.forEach(p => {
            return null;
        });

3.去重

3.1List<> 去重

import java.util.stream.Collectors;

List<Material> newList = list.stream().distinct().collect(Collectors.toList());
//方式二
List<String> list=new ArrayList<>();
list.add("a");
list.add("b");
list.add("b");
list.stream().distinct().forEach(item ->System.out.println(item));
//输出:"a"
//		"b"
3.2 数组 去重
 int[] a={1,2,2,3,3,5,4,4,8,6,18};
 List<Integer> aa =Arrays.stream(a).distinct().boxed().collect(Collectors.toList());
 
String[] str ={"a","a","b"};
List<String> newstr  =Arrays.stream(str ).distinct().collect(Collectors.toList());

4.判断List集合中对象的某个字段是否存在重复值

原作者:https://blog.youkuaiyun.com/weixin_42023748/article/details/122104437

         Person person1 = new Person("小刘", 24, "男");
        Person person2 = new Person("小贺", 18, "女");
        Person person3 = new Person("小袁", 18, "女");
        Person person4 = new Person("小李", 21, "男");
        Person person5 = new Person("小子", 21, "男");
        List<Person> persons = Arrays.asList(person1, person2, person3, person4,person5);
 
        // 根据指定属性分组,并统计数量(key:指定属性,value:数量)
        //Map<Object, Long> mapGroup = persons.stream().collect(Collectors.groupingBy(person -> person.getAge(), Collectors.counting()));//我试了,.get得不到属性
         Map<Object, Long> mapGroup = persons.stream().collect(Collectors.groupingBy(Person ::getAge, Collectors.counting()));

        System.out.println(mapGroup.toString());
 
        // 筛选Map中value大于1的key
        Stream<Object> stringStream = mapGroup.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey());
        System.out.print("重复的数据:{ ");
        stringStream.forEach(str -> {
            System.out.print(str + " ");
        });
        System.out.println("}");
    }

4.1某个字段是否存在重复值

public static void main(String[] args) {
         Person person1 = new Person("小刘", 24, "男");
        Person person2 = new Person("小贺", 18, "女");
        Person person3 = new Person("小袁", 18, "女");
        Person person4 = new Person("小李", 21, "男");
        Person person5 = new Person("小子", 21, "男");
        List<Person> persons = Arrays.asList(person1, person2, person3, person4,person5);
 
        // 根据指定属性分组,并统计数量(key:指定属性,value:数量)
        Map<Object, Long> mapGroup = persons.stream().collect(Collectors.groupingBy(person -> person.getAge(), Collectors.counting()));
        System.out.println(mapGroup.toString());
 
        // 筛选Map中value大于1的key
        Stream<Object> stringStream = mapGroup.entrySet().stream().filter(entry -> entry.getValue() > 1).map(entry -> entry.getKey());
        System.out.print("重复的数据:{ ");
        stringStream.forEach(str -> {
            System.out.print(str + " ");
        });
        System.out.println("}");
    }

4.2判断List集合中对象的某个字段是否存在重复值

public static void main(String[] args) {
        List<User> userList = new ArrayList<>();
        
        userList.add(new User("1","李大锤","23","南京"));
        userList.add(new User("2","张无忌","18","西安"));
        userList.add(new User("3","刘德华","26","苏州"));
        userList.add(new User("4","郭靖","33","上海"));
        
        userList.add(new User("1","李大锤","23","南京"));    //id相同,其他数据也相同
        userList.add(new User("3","带头大哥","36","杭州"));  //id相同,其他数据不同
        
        System.out.println(userList);
        //根据userid去重
        userList = userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User :: getUserid))), ArrayList::new));
        System.out.println(userList);
    }
// 2. 多个字段去重
 
List<User> collect = 
userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getSex() + "#" + o.getAddre()))), ArrayList::new));

5.List<>分组

/**
				 * 1、过滤出子物料
				 * 2、按照主物料Component,进行分组
				 */
				Map<String, List<ProductMaterialDTO>> subMap = listMaterialDTOs.stream()
						.filter(item -> item.getParentScrapId() != null && item.getParentScrapId() > 0)
						.map(p -> p.cloneDTO())//拷贝对象,避免引用对象,导致环形链,引发死循环
						.collect(Collectors.groupingBy(item-> item.getParentComponent()));

// 遍历e
for (Map.Entry<String, List<WarehouseConfig>> entryList : siteCodeMap.entrySet()){
			List<WarehouseConfig> allMaterial =  entryList.getValue();
}

6.List转Map

Map<String, Object>
Map<String, List>

Map<String, UserDto> userMap = userList.stream()
            .collect(Collectors.toMap(UserDto::getName, dto2 -> dto2))

Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId,Person::getName));
//key重复
//重复时用后面的value 覆盖前面的value
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key2 ));
//重复时将前面的value 和后面的value拼接起来
Map<String, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName,(key1 , key2)-> key1+","+key2 ));

//数据组成集合
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
	    		p ->  {
	    		 	List<String> getNameList = new ArrayList<>();
	    		 		getNameList.add(p.getName());
	    		 		return getNameList;
	    		 	},
    		     	(List<String> value1, List<String> value2) -> {
    		     		value1.addAll(value2);
    		     		return value1;
    		     	}
	    		 ));
       
//判空,即便value为空,依旧输出
Map<String, List<String>> map = list.stream().collect(Collectors.toMap(Person::getId,
	    		p ->  {
	    		 	List<String> getNameList = new ArrayList<>();
	    		 		getNameList.add(p.getName());
	    		 		return getNameList;
	    		 	},
    		     	(List<String> value1, List<String> value2) -> {
    		     		value1.addAll(value2);
    		     		return value1;
    		     	}
	    		 ))




6.List中map()用法

List<Application>  appList = applicationMapper.list(qo);
		List<Application> iApp = appList.stream().map(app -> new Integer(Application::getId)
				.collect(Collectors.toList());
		List<Integer> iApp = appList.stream().map(app -> new Integer( app.getId().split("-")[0]))
				.collect(Collectors.toList());
		
		Integer maxAppNo = iApp.stream().max(Integer::compareTo).orElse(0);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值