List转Map
List<Apple> appleList = new ArrayList<>();//存放apple对象集合
1. List转Map
id为key,apple对象为value,可以这么做:
/** * List -> Map * 需要注意的是: * toMap 如果集合对象有重复的key,会报错Duplicate key ....
* apple1,apple12的id都为1。 * 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2 */ Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
Map<String, ManagerCollectDTO> partsMap = lastNodeData.stream().collect(Collectors.toMap(k -> k.getEmployeeId()+k.getStoreId(), part -> part));
打印appleMap:
{1=Apple{id=1, name='苹果1', money=3.25, num=10}, 2=Apple{id=2, name='苹果2', money=2.89, num=30}, 3=Apple{id=3, name='苹果3', money=9.99, num=40}}
2. 分组
List里面的对象元素,以某个属性来分组,例如,以id分组,将id相同的放在一起:
Map<Integer, List<User>> groupBy = appleList.stream().collect(Collectors.groupingBy(User::getId));
3. 过滤filter
从集合中过滤出来符合条件的元素:
//过滤出符合条件的数据
getSource()==5的数据
List<AppointOrderDTO> filter3= filter.stream().filter(a -> a.getSource()==5).collect(Collectors.toList());
4.去重
<--单条件-->
List<ClassMember> list1 = list.stream().collect( Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>( Comparator.comparing(ClassMember::getStartTime))),ArrayList::new));
<--多条件-->
List<AppointOrderDTO> list2 = list1.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(()->new TreeSet<>(
Comparator.comparing(a->a.getPayOrderDate()+";"+a.getAppointUserId()))), ArrayList::new));
5.排序
正序:
sysLogDTOS.sort(Comparator.comparing(SysLogDTO::getDate));
倒序
sysLogDTOS = sysLogDTOS.stream().sorted(Comparator.comparing(SysLogDTO::getDate).reversed())
.collect(Collectors.toList());
升序时,属性值为空排前面
list.sort(Comparator.comparing(Project::getId,Comparator.nullsFirst(Integer::compareTo)));
升序时,属性值为空排后面
list.sort(Comparator.comparing(Project::getId,Comparator.nullsLast(Integer::compareTo)));
降序时,属性值为空排到后面
list.sort(Comparator.comparing(Project::getId,Comparator.nullsFirst(Integer::compareTo)).reversed());
降序时,属性值为空排到前面
list.sort(Comparator.comparing(Project::getId,Comparator.nullsLast(Integer::compareTo)).reversed());
6. 求和
将集合中的数据按照某个属性求和:
通过 sum()
方法实现(两种方式):
public static void answer() { List<Student> students = initData(); Double result = students.stream() .filter(one -> one.getScore() >= 60).map(o -> o.getScore()) .reduce(0d, (a,b) -> (a + b)); System.out.println(result); }
public static void answerSecondImpl() { List<Student> students = initData(); Double result = students.stream() .filter(one -> one.getScore() >= 60).mapToDouble(o -> o.getScore()).sum(); System.out.println(result); }
BigDecimal:
//计算 总金额 BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add); System.err.println("totalMoney:"+totalMoney); //totalMoney:17.48
Integer:
//计算 数量 int sum = appleList.stream().mapToInt(Apple::getNum).sum(); System.err.println("sum:"+sum); //sum:100