项目中常用的JDK8之Stream流,长期补充
1、JDK8 List转Map
public class ListToMapExample { public static void main(String[] args) { List<User> users = Arrays.asList( new User(1, "Alice"), new User(2, "Bob"), new User(3, "Charlie") ); Map<Integer, User> userMap = users.stream().collect(Collectors.toMap(User::getId, user -> user)); userMap.forEach((id, user) -> System.out.println(id + " -> " + user.getName())); } }
2、JDK8从集合中根据条件查找元素
假如集合groupOpts是List<HashMap<String,String>>类型,现在要查找groupOpts中HashMap键为id,值为123456的元素,找不到就返回null。 1.返回一个元素 HashMap<String, String> groupOpt = groupOpts.stream().filter(group -> "123456".equals(group.get("id"))).findAny().orElse(null); 2.返回符合条件多个元素 List<HashMap<String, String>> collect = groupOpts.stream().filter(tag -> "123456".equals(group.get("id"))).collect(Collectors.toList());
3、JDK8 对集合中某类进行合计
BigDecimal rkChaoShiWeight = inboundOvertimeAlarmOrderList.stream().map(order -> order.getOrderWeight()).reduce(BigDecimal.ZERO, BigDecimal::add);