fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.stream.Collectors;
  5.  
  6. /* Name of the class has to be "Main" only if the class is public. */
  7. class Ideone
  8. {
  9. public static void main ( String[] args ) throws java.lang.Exception
  10. {
  11. List < CountryCount > listOfCountryCount = List.of(
  12. new CountryCount( "Peru" , 17L ) ,
  13. new CountryCount( "Xanadu" , 128L ) ,
  14. new CountryCount( null , 42L ) ,
  15. new CountryCount( "Andorra" , null )
  16. );
  17.  
  18. NavigableMap < String, Long > map =
  19. listOfCountryCount
  20. .stream()
  21. .collect(
  22. Collectors.toMap(
  23. countryCount -> Objects.isNull( countryCount.getCountry() ) ? "unknown" : countryCount.getCountry() ,
  24. countryCount -> Objects.isNull( countryCount.getCount() ) ? Long.valueOf( 0 ) : countryCount.getCount() ,
  25. ( existing , replacement ) -> existing , // In case of duplicate key conflict, first one wins.
  26. TreeMap :: new
  27. )
  28. );
  29.  
  30. System.out.println( "listOfCountryCount = " + listOfCountryCount );
  31. System.out.println( "map = " + map );
  32. }
  33. }
  34.  
  35. final class CountryCount
  36. {
  37. private final String country;
  38. private final Long count;
  39.  
  40. CountryCount ( String country , Long count )
  41. {
  42. this.country = country;
  43. this.count = count;
  44. }
  45.  
  46. public String getCountry ( ) { return country; }
  47.  
  48. public Long getCount ( ) { return count; }
  49.  
  50. @Override
  51. public boolean equals ( Object obj )
  52. {
  53. if ( obj == this ) return true;
  54. if ( obj == null || obj.getClass() != this.getClass() ) return false;
  55. var that = ( CountryCount ) obj;
  56. return Objects.equals( this.country , that.country ) &&
  57. Objects.equals( this.count , that.count );
  58. }
  59.  
  60. @Override
  61. public int hashCode ( )
  62. {
  63. return Objects.hash( country , count );
  64. }
  65.  
  66. @Override
  67. public String toString ( )
  68. {
  69. return "CountryCount[" +
  70. "country=" + country + ", " +
  71. "count=" + count + ']';
  72. }
  73. }
Success #stdin #stdout 0.14s 55312KB
stdin
Standard input is empty
stdout
listOfCountryCount = [CountryCount[country=Peru, count=17], CountryCount[country=Xanadu, count=128], CountryCount[country=null, count=42], CountryCount[country=Andorra, count=null]]
map = {Andorra=0, Peru=17, Xanadu=128, unknown=42}