Collectors.GroupBy示例:如何在Java中进行分组
时间:2020-02-23 14:34:18 来源:igfitidea点击:
在本教程中,我们将看到Java 8 Collectors GroupBy示例。
GroupBy是Java 8中添加的另一个功能,它非常类似于SQL/Oracle。
让我们在榜样的帮助下更多地理解:让我们创建我们的模型类国家,如下所示:
package org.igi.theitroad;
public class Country{
String countryName;
long population;
public Country() {
super();
}
public Country(String countryName,long population) {
super();
this.countryName = countryName;
this.population=population;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public long getPopulation() {
return population;
}
public void setPopulation(long population) {
this.population = population;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((countryName == null) ? 0 : countryName.hashCode());
result = prime * result + (int) (population ^ (population >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Country other = (Country) obj;
if (countryName == null) {
if (other.countryName != null)
return false;
} else if (!countryName.equals(other.countryName))
return false;
if (population != other.population)
return false;
return true;
}
public String toString()
{
return "{"+countryName+","+population+"}";
}
}
允许我们创建主类,我们将使用收藏家.groupby来做组。
package org.igi.theitroad;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Java8CollectorsGroupBy {
public static void main(String[] args) {
List items = Arrays.asList(new Country("Netherlands", 20000),
new Country("China", 40000), new Country("Nepal", 30000),
new Country("Netherlands", 50000), new Country("China", 10000));
//Group by countryName
Map<String, List> groupByCountry = items.stream().collect(
Collectors.groupingBy(Country::getCountryName));
System.out.println(groupByCountry.get("Netherlands"));
//Group by CountryName and calculates the count
Map<String, Long> counting = items.stream().collect(
Collectors.groupingBy(Country::getCountryName,Collectors.counting()));
//Group by countryName and sum up the population
System.out.println(counting);
Map<String, Long> populationCount = items.stream().collect(
Collectors.groupingBy(Country::getCountryName,
Collectors.summingLong(Country::getPopulation)));
System.out.println(populationCount);
}
}
运行上面的类时,我们将得到以下输出:
[{Netherlands,20000}, {Netherlands,50000}]
{China=2, Nepal=1, Netherlands=2}
{China=50000, Nepal=30000, Netherlands=70000}

