how stream().distinct() works - list of maps

sample code below:

 

package homeWork;

 

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.stream.Collectors;

 

public class distinctSample {

 

public static void main(String[] args) {

 

List<Map<String, Object>> countries = new ArrayList<Map<String, Object>>();

 

Map<String, Object> country;

 

country = new HashMap<String, Object>();

country.put( "collectYM",   "201801" );

country.put( "population", 1000 );

countries.add( country );

 

country = new HashMap<String, Object>();

country.put( "collectYM",   "201802" );

country.put( "population", 1200 );

countries.add( country );

 

country = new HashMap<String, Object>();

country.put( "collectYM",   "201804" );

country.put( "population", 800 );

countries.add( country );

 

country = new HashMap<String, Object>();

country.put( "collectYM",   "201803" );

country.put( "population", 1000 );

countries.add( country );

 

country = new HashMap<String, Object>();

country.put( "collectYM",   "201803" );

country.put( "population", 1000 );

countries.add( country );

 

countries.stream().forEach(System.out::println);

 

System.out.println("total of list:" + countries.size());

 

System.out.println("distinct count:" + countries.stream().distinct().count());

 

 

 

List<Map<String, Object>> countries_distinct=new ArrayList<Map<String, Object>>();

countries_distinct.addAll(countries.stream().distinct().collect(Collectors.toList()));

 

countries_distinct.stream().forEach(System.out::println);

 

}

 

}

result:

 

f:id:annazola:20191016225657p:plain