Home > Blockchain >  Java Filter Array using Filter and Stream
Java Filter Array using Filter and Stream

Time:05-31

There are 2 Classes "Country" and "City"

Country has Countrycode , Countryname , capital , population , Continent and an array of Type City as Attributes.

City has Countrycode,name and population as Attributes .

I am trying to find the highest populated city of each Country.

I want to use the .stream Library

import java.util.ArrayList;
import java.util.Comparator;
import java.util.NoSuchElementException;

public class Main13 {

    public static void main(String[] args) {
        
        ArrayList<Country> Countries=new ArrayList<Country>();
        
        //Countrycode,Countryname,capital,population,Continent
        
        Country coun1=new Country(1,"Japan","Tokyo",4000000,"Asia");
        Country coun2=new Country(2,"USA","DC",400000000,"America");
        
        
        City c1=new City(1,"Tokyo",100000);
        City c2=new City(1,"Osaka",10000);
        City c3=new City(1,"Nagoya",20000);
        
        City n1=new City(2,"NYC",4000000);
        City n2=new City(2,"LA",1000000);
        
        
        coun1.Cities.add(c1);
        coun1.Cities.add(c2);
        coun1.Cities.add(c3);
        
        coun2.Cities.add(n1);
        coun2.Cities.add(n2);
        
        Countries.add(coun1);
        Countries.add(coun2);
        
        Country Max2=Countries.stream().max(Comparator.comparingInt(Country::getpop)).orElseThrow(NoSuchElementException::new);
        
        System.out.println(Max2.Countryname);
    }

}

////////////////////////////////////////////
import java.util.ArrayList;
import java.util.List;

public class Country {
    int countrycode;
    String Countryname; 
    String Capital; 
    int Population;
    String Continent; 
    ArrayList<City> Cities=new ArrayList<City>();

    public Country(int code,String n,String c,int p,String con) {
        countrycode=code;
        Countryname=n; 
        Capital=c; 
        Population=p;
        Continent=con;
    }

    public int getpop() {
        return Population;
    }

}
////////////////////////

public class City {

    int CountryCode;
    String name;
    int Population;
    
    
    
    public City(int code,String n,int pop) {
        CountryCode=code;
        name=n;
        Population=pop;
    }
}

CodePudding user response:

As you want to do something for each country, you need to loop on the coutries, then apply the logic

for (Country c : countries) {
    City max2 = c.cities.stream().max(Comparator.comparingInt(City::getPopulation))
            .orElseThrow(NoSuchElementException::new);
    System.out.println(c.getName()   " "   max2.getName()   " "   max2.getPopulation());
}
Japan Tokyo 100000
USA NYC 4000000

Note : java variable naming convention is lowerCamelCase

class Country {
    int code;
    String name;
    String capital;
    int population;
    String continent;
    List<City> cities;
}
  • Related