Talking about the processing of array data java--Stream

Regarding the processing of some array data, some commonly used methods are recorded here to prevent yourself from forgetting and looking for it.

Generally speaking, the processing of some lists involves grouping, sorting, merging, positioning, etc., and interaction with the database may be involved in the middle. Of course, some jar packages have better encapsulation of array data. You can pay attention to it. , To prevent yourself from needing to use "special" methods to achieve it is not only troublesome, but also not elegant.

1. Data in batches

Some batch data processing involves data grouping.

List<Integer> list = Arrays.asList(23, 18, 20, 2, 12, 9, 6, 14, 1, 87, 15, 99);
//1、直接分组(推荐)
 List<List<Integer>> partition = Lists.partition(list, 10); //10个一组,封装到partition中
//2、可以个人处理
 int num = list.size()/10 + list.size()%10==0?0:1; //计算要切割成几份
 // 然后使用循环截取。不过要注意的是要和list的大小比较,防止下标溢出       
      for (int i = 0; i < num; i++) {
            if((i+1)*10<list.size()){
                List<Integer> integerList = list.subList(i * 10, (i + 1) * 10);
                // integerList to do sth
            } else {
                List<Integer> integerList = list.subList(i * 10, list.size());
                // integerList to do sth
            }
        }

2. Data summation

   List<Book> bookList = new ArrayList<>();
        // BigDecimal类型求和
        BigDecimal sum = bookList.stream().map(book -> book.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);

        // int、double、long类型求和
        int sumInt = bookList.stream().mapToInt(book -> book.getWidth()).sum();
        long sumLong = bookList.stream().mapToLong(book -> book.getLength()).sum();
        double sumDouble = bookList.stream().mapToDouble(book -> book.getHight()).sum();

3. Customized sorting

//定制排序,可以根据条件定义排序,一个或多个条件均可以,下面适示意的是从大到小排序
// 判断条件是自己写的,可以根据需要来,仿写的话没啥大问题哈
public class Book implements Comparable<Book> {

    private String name;

    private BigDecimal price ;

    private Long length;

    private Integer width;

    private Double hight;

    @Override
    public int compareTo(Book o) {
        if(o.getWidth()>this.getWidth()){
            return 1;
        } else if(o.getWidth()<this.getWidth()){
            return -1;
        }
        return 0;
    }
 }

4. Data is grouped according to conditions

I don’t know if you have encountered it before, but it is also more commonly used. For example, if you find some books, group them according to the person where the books are located. Of course, this can also be done in the database, but sometimes it needs to be processed in the code. . There is also a batch of subqueries, and then when the data is corresponding, it is a group of corresponding groups.


        List<Book> bookList = new ArrayList<>();

        Book book = new Book();
        book.setWidth(12);
        book.setName("Ebook");
        bookList.add(book);

        Book book1 = new Book();
        book1.setWidth(2);
        book1.setName("java");
        bookList.add(book1);

        Book book2 = new Book();
        book2.setWidth(17);
        book2.setName("java");
        bookList.add(book2);

        Map<String, List<Book>> groupMap= bookList.stream().collect(Collectors.groupingBy(vo -> vo.getName()));

        System.out.println(JSON.toJSONString(groupMap));

The printout is grouped by name:

{"java":[{"name":"java","width":2},{"name":"java","width":17}],"Ebook":[{"name":"Ebook","width":12}]}

The grouping process uses vo -> vo.getName(), you can implement your own logic according to your needs

5. Data is processed by key and value

Sometimes an object may need to be split into the form of key and value to facilitate subsequent operations. There are also ways to help deal with this.

       List<Book> bookList = new ArrayList<>();

        Book book = new Book();
        book.setWidth(12);
        book.setName("Ebook");
        bookList.add(book);

        Book book1 = new Book();
        book1.setWidth(2);
        book1.setName("java");
        bookList.add(book1);

        Book book2 = new Book();
        book2.setWidth(17);
        book2.setName("java");
        bookList.add(book2);
        
        // 这个是固定写法,后面的 (p1, p2) -> p2)是指如果有两个value相同,是选择前一个p1,还是选择后一个p2作为map的value,如下,名称java对应的就是后一个了(17),value覆盖
        Map<String, Integer> map = bookList.stream().collect(Collectors.toMap(voKey -> voKey.getName(), voValue -> voValue.getWidth(), (p1, p2) -> p2));
        System.out.println(JSON.toJSONString(map));

Of course, you can also accumulate or concatenate values ​​with the same key.

       Map<String, Integer> map = bookList.stream().collect(Collectors.toMap(voKey -> voKey.getName(), voValue -> voValue.getWidth(), (p1, p2) -> p1+p2));

Supplement: 6. Filter to remove duplication

De-duplicate according to a field

        List<Book> bookList = new ArrayList<>();
        bookList.add(new Book("语文书", "12.3", "张三"));
        bookList.add(new Book("语文书", "12.3", "李四"));
        bookList.add(new Book("数学书", "16.3", "张三"));
        bookList.add(new Book("英语书", "11.3", "王五"));
        bookList.add(new Book("数学书", "16.3", "何柳"));
        // 过滤掉bookList中 书籍相同的数据
        List<Book> resultList = bookList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->
                new TreeSet<>(Comparator.comparing(Book::getName))), ArrayList::new));
        System.out.println("结果:" + JSONArray.toJSONString(resultList));

The result is printed:

结果:[{"author":"张三","name":"数学书","price":"16.3"},{"author":"王五","name":"英语书","price":"11.3"},{"author":"张三","name":"语文书","price":"12.3"}]


It depends on your own needs. If you need other complex processing, you can also implement it, but if it is more complex, you should consider your own design and see if you can optimize the design~

There is only so much list processing that I think of temporarily, so let's add it when I think of it later!

Give me a compliment if it looks okay~

No sacrifince ,no victory!

Guess you like

Origin blog.csdn.net/zsah2011/article/details/108848401