With the new JAVA8 feature, you can use simple and efficient code to implement some data processing.
Define 1 apple objects:
publicclass Apple { private Integer id; private String name; private BigDecimal money; private Integer num; publicApple(Integer id, String name, BigDecimal money, Integer num) { this.id = id; this.name = name; this.money = money; this.num = num; }}
Add some test data:
Apple Apple1 =New Apple(1,"Apple 1",NewBigDecimal ("3.25"),Ten); Apple Apple2 =New Apple(1,"Apple 2",NewBigDecimal ("1.35"), -); Apple Apple3 =New Apple(2,"Banana",NewBigDecimal ("2.89"), -); Apple apple4 =New Apple(3,"Litchi",NewBigDecimal ("9.99"), +); List<apple> applelist = Lists.newarraylist(Apple1, Apple2, Apple3, apple4);
1. Grouping
The object element in the list, grouped by an attribute, for example, grouped by ID, together with the same ID:
//List 以ID分组 Map<Integer,List<Apple>>Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
2. List Transfer map
ID is Key,apple object is value, you can do this:
/** * 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));
3. Filtering Filter
Filter out the elements that match the criteria from the collection:
//过滤出符合条件的数据List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
4. Summation
Sums the data in the collection according to a property:
//计算 总金额BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
5. Find the maximum minimum value in the stream
Collectors.maxby and Collectors.minby to calculate the maximum or minimum value in the stream.
Optional<Dish> maxDish = Dish.menu.stream(). collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));maxDish.ifPresent(System.out::println);Optional<Dish> minDish = Dish.menu.stream(). collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));minDish.ifPresent(System.out::println);
6. Go to the heavy
// 根据id去重 List<Person> unique = appleList.stream().collect( collectingAndThen(toCollectionnew TreeSet<>(comparingLong(Apple::getId))), ArrayList::new) );
Ref: 77595585
JAVA8 Implementing various list operations