package com.java.util;
import java.util.*;
import java.util.stream.Collectors;
public class CollectorsGroupBy {
public static void main(String[] args) {
List<Country> items = Arrays.asList(
new Country("India", 1700000),
new Country("India", 5000000),
new Country("USA", 400000),
new Country("USA", 800000),
new Country("Germany", 300000)
);
// Group by CountryName and calculates the count
Map<String, Optional<Country>> counting = items.stream().collect(
Collectors.groupingBy(Country::getName, Collectors.maxBy(Comparator.comparing(Country::getPopulation))));
for (Map.Entry<String, Optional<Country>> item : counting.entrySet()) {
Country country = item.getValue().get();
System.out.println(country.getName());
System.out.println(country.getPopulation());
for (Country co : items) {
if (country.getName().equals(co.getName())) {
co.setPopulation(country.getPopulation());
}
}
}
items.forEach(System.out::println);
}
}
package com.java.util;
public class Country{
String name;
long population;
public Country() {
super();
}
public Country(String name,long population) {
super();
this.name = name;
this.population=population;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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
+ ((name == null) ? 0 : name.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 (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (population != other.population)
return false;
return true;
}
public String toString()
{
return "{"+ name +","+population+"}";
}
}
