Java8 using the new features with simple and efficient code to implement some data processing

Apple defined a target:

public class Apple {
    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;
    public Apple(Integer id, String name, BigDecimal money, Integer num) {
        this.id = id;
        this.name = name;
        this.money = money;
        this.num = num;
    }
}
添加一些测试数据:
List<Apple> appleList = new ArrayList<>();//存放apple对象集合
 
Apple apple1 =  new Apple(1,"苹果1",new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1,"苹果2",new BigDecimal("1.35"),20);
Apple apple2 =  new Apple(2,"香蕉",new BigDecimal("2.89"),30);
Apple apple3 =  new Apple(3,"荔枝",new BigDecimal("9.99"),40);
 
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);

1, the packet
objects List elements inside, grouped in an attribute, for example, to a packet id, the id of the same together:

//List 以ID分组 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
 
System.err.println("groupBy:"+groupBy);
{1=[Apple{id=1, name='苹果1', money=3.25, num=10}, Apple{id=1, name='苹果2', money=1.35, num=20}], 2=[Apple{id=2, name='香蕉', money=2.89, num=30}], 3=[Apple{id=3, name='荔枝', money=9.99, num=40}]}

2, List transfer the Map
the above mentioned id as the key, apple object value, you can do this:

/ **
 * List -> the Map
 * Note that:
 * toMap collection object if there are duplicate key, will complain .... Key Duplicate
 * apple1, apple12's id is 1.
 * Can be (k1, k2) -> k1 is set, if there are duplicate key, is retained key1, discard key2
 * /
the Map <Integer, the Apple> appleMap = appleList.stream () the collect (Collectors.toMap (the Apple:. : getId, a -> a, (k1, k2) -> k1));
print appleMap
{. 1 = the Apple {ID =. 1, name = 'apple 1', money = 3.25, num = 10}, 2 = Apple { id = 2, name = 'banana', money = 2.89, num = 30}, 3 = Apple {id = 3, name = ' lychee', money = 9.99, num = 40}}

3, the filter Filter
filtered out from the collection element matches:

// display the required data
List <Apple> filterList = appleList.stream ( ) filter (a -> a.getName () equals ( " banana").) The collect (Collectors.toList ());..
 
The System. err.println ( "FilterList:" FilterList +);
[{the Apple ID = 2, name = 'banana', money = 2.89, num = 30}]

4. summing
the data set according to an attribute summation:

//计算 总金额
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney);  //totalMoney:17.48


5. Find the maximum and minimum flow
calculated maximum or minimum flow Collectors.maxBy and Collectors.minBy.


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.去重
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
 
// 根据id去重
     List<Person> unique = appleList.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)
        );

 

The following table shows the static factory method Collectors class.

Factory method return type role
toList List <T> to stream all items collected in a List
toset the Set <T> to stream all the items collected to a Set, remove duplicates
toCollection Collection <T> to stream all items collected to give set menuStream.collect (toCollection (), ArrayList :: new) given supply source to create
a stream of counting the number of elements in the counting Long
a convection sumInt integer integer attribute items summed
average averagingInt Double integer items calculate the flow properties value
summarizingInt IntSummaryStatistics collect statistics about the flow Integer property item, such as maximum, minimum, sum and average
joining string call connection method of each item in the stream generated string toString the collect (joining ( ","))
maxBy Optional the <T> stream in accordance with a package of a given maximum element Optional comparator selected, or if the stream is empty compared Optional.empty ()
minBy Optional <T> a selected package flow in a given comparator Optional smallest element, or if the stream is empty Optional.empty ()
Reducing type reduction operations generated as an initial value of the accumulator from the start of a use of the element BinaryOperator individually combined stream so as to flow together around a single value accumulated int totalCalories = menuStream.collect (reducing (0 , Dish :: getCalories, Integer :: SUM));
collectingAndThen conversion function returns the type of package to another collector, the conversion results of its application howManyDishes = menuStream.collect function int (collectingAndThen (toList (), List :: size))
groupingBy the Map <K , List <T >> set as Q according to the value of an attribute item convection items and attribute values as a result of the Map key
partitioningBy Map <Boolean, List <T >> results convection predicate applied according to each item to partition the project

 

Transfer from https://blog.csdn.net/qq_33609401/article/details/84862721

Guess you like

Origin www.cnblogs.com/luizw/p/10978188.html