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);