Java8 can quickly realize list to map, grouping, filtering and other operations

Using the new features of Java 8, you can use simple and efficient code to realize some data processing.

Define 1 apple object:

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

Add some test data:

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. Grouping

The object elements in the list are grouped by a certain attribute. For example, they are grouped by ID, and the objects with the same ID are put 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 to map

If the ID is key and the 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));
打印appleMap
{1=Apple{id=1,2=Apple{id=2,num=30},3=Apple{id=3,num=40}}

3. Filter

Filter out qualified elements from the collection:

//过滤出符合条件的数据
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());

System.err.println("filterList:"+filterList);
[Apple{id=2,num=30}]

4. Summation

Sum the data in the collection according to an attribute:

//计算 总金额
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 values in the flow

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. Weight removal

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 methods of the collectors class.

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>