Java 8 – Stream Collectors groupingBy examples 修改教程

在这篇教程中,将向你展示如何使用Java 8 Stream的Collectors,来对一个List进行分组,计算个数,求和以及排序。

1. Group By, Count and Sort

1.1 对一个List进行分组,并显示每组的个数

Java8Example1.java

package com.mkyong.java8;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8Example1 {

    public static void main(String[] args) {

        //3 apple, 2 banana, others 1
        List<string> items =
                Arrays.asList("apple", "apple", "banana",
                        "apple", "orange", "banana", "papaya");

        Map<string, long=""> result =
                items.stream().collect(
                        Collectors.groupingBy(
                                Function.identity(), Collectors.counting()
                        )
                );

        System.out.println(result);


    }
}

output

{
    papaya=1, orange=1, banana=2, apple=3
}

1.2 加入排序

Java8Example2.java

package com.mkyong.java8;

import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Java8Example2 {

    public static void main(String[] args) {

        //3 apple, 2 banana, others 1
        List<string> items =
                Arrays.asList("apple", "apple", "banana",
                        "apple", "orange", "banana", "papaya");

        Map<string, long=""> result =
                items.stream().collect(
                        Collectors.groupingBy(
                                Function.identity(), Collectors.counting()
                        )
                );

        Map<string, long=""> finalMap = new LinkedHashMap&lt;&gt;();

        //Sort a map and add to finalMap
        result.entrySet().stream()
                .sorted(Map.Entry.<string, long="">comparingByValue()
                        .reversed()).forEachOrdered(e -&gt; finalMap.put(e.getKey(), e.getValue()));

        System.out.println(finalMap);


    }
}

output

{
    apple=3, banana=2, papaya=1, orange=1
}

2. List Objects

对用户定义的对象数组进行分组的例子。

2.1 一个简单java对象.

Item.java

package com.mkyong.java8;

import java.math.BigDecimal;

public class Item {

    private String name;
    private int qty;
    private BigDecimal price;

    //constructors, getter/setters 
}

2.2 通过name属性分组,并显示分组个数或Qty属性的数量

Java8Examples3.java

package com.mkyong.java8;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8Examples3 {

    public static void main(String[] args) {

        //3 apple, 2 banana, others 1
        List<item> items = Arrays.asList(
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 20, new BigDecimal("19.99")),
                new Item("orang", 10, new BigDecimal("29.99")),
                new Item("watermelon", 10, new BigDecimal("29.99")),
                new Item("papaya", 20, new BigDecimal("9.99")),
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 10, new BigDecimal("19.99")),
                new Item("apple", 20, new BigDecimal("9.99"))
        );

        Map<string, long=""> counting = items.stream().collect(
                Collectors.groupingBy(Item::getName, Collectors.counting()));

        System.out.println(counting);

        Map<string, integer=""> sum = items.stream().collect(
                Collectors.groupingBy(Item::getName, Collectors.summingInt(Item::getQty)));

        System.out.println(sum);

    }
}

output

//Group by + Count
{
    papaya=1, banana=2, apple=3, orang=1, watermelon=1
}

//Group by + Sum qty
{
    papaya=20, banana=30, apple=40, orang=10, watermelon=10
}

2.2 通过Price分组 – 使用Collectors.groupingByCollectors.mapping 的例子.

Java8Examples4.java

package com.mkyong.java8;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Java8Examples4 {

    public static void main(String[] args) {

        //3 apple, 2 banana, others 1
        List<item> items = Arrays.asList(
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 20, new BigDecimal("19.99")),
                new Item("orang", 10, new BigDecimal("29.99")),
                new Item("watermelon", 10, new BigDecimal("29.99")),
                new Item("papaya", 20, new BigDecimal("9.99")),
                new Item("apple", 10, new BigDecimal("9.99")),
                new Item("banana", 10, new BigDecimal("19.99")),
                new Item("apple", 20, new BigDecimal("9.99"))
                );

        //group by price
        Map<BigDecimal, List<Item>> groupByPriceMap = 
            items.stream().collect(Collectors.groupingBy(Item::getPrice));

        System.out.println(groupByPriceMap);

        // group by price, uses 'mapping' to convert List<Item> to Set<String>
        Map<BigDecimal, Set<String>> result =
                items.stream().collect(
                        Collectors.groupingBy(Item::getPrice,
                                Collectors.mapping(Item::getName, Collectors.toSet())
                        )
                );

        System.out.println(result);

    }
}

output

{
    19.99=[
            Item{name='banana', qty=20, price=19.99}, 
            Item{name='banana', qty=10, price=19.99}
        ], 
    29.99=[
            Item{name='orang', qty=10, price=29.99}, 
            Item{name='watermelon', qty=10, price=29.99}
        ], 
    9.99=[
            Item{name='apple', qty=10, price=9.99}, 
            Item{name='papaya', qty=20, price=9.99}, 
            Item{name='apple', qty=10, price=9.99}, 
            Item{name='apple', qty=20, price=9.99}
        ]
}

//group by + mapping to Set
{
    19.99=[banana], 
    29.99=[orang, watermelon], 
    9.99=[papaya, apple]
}

References

  1. Java 8 Stream Collectors JavaDoc
  2. Java – How to sort a Map
  3. [Stackoverflow – Sort a Map by values (Java) ][Stackoverflow _ Sort a Map by values Java]

[Stackoverflow _ Sort a Map by values Java]: http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java

如果觉得JSRUN的教程对您有用,请随意打赏。您的支持将鼓励JSRUN继续提供更好的服务

捐助JSRUN
JSRUN前端教程共编系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的本前端教程,让知识的积累变得统一完整、自成体系。 希望广大工程师能一起参与进共编,让零散在世界各处的知识点找到组织、找到家。
X
支付宝
9.99
请使用支付宝扫码支付, 有效时间 5分0秒
超过有效时间后请立即停止支付。
支付故障请联系QQ:565830900
因10.00元通道已占用,系统建议您支付9.99元
正在生成二维码, 此过程可能需要15秒钟
谢谢支持,我一定会更加努力的