### Functional Interfaces and Lambda Expressions
------------------------------------------------
1. In the class LambdaExercise, create following static variables
1. countries of type List<String>
2. countryCapitals of type Map<String, String>
In a static block, initialize countries and countryCapitals with soe values
Define following static methods and provide the implementation as given below
- sortCountriesBylength
- Sort the List using Comparator, in descending order of number of characters in the country name.
If the number of characters are same for a country, it should be sorted alphabetically
(Use Comparator's static/default methods)
- removeCountry(String name)
- remove the countries whose name is greater than 6 characters
Execute the methods and display the results in main method
import java.util.List;
public class Main{
public static int getPop_Loop(List<Country> countries, String conti) {
int totalP = 0;
for (Country country : countries) {
if (country.getContinent().equalsIgnoreCase(conti)) {
totalP += country.getPop();
}
}
return totalP;
}
public static int getPop_Lambda(List<Country> countries, String conti) {
return countries.stream().filter(country -> country.getContinent().equalsIgnoreCase(conti)).mapToInt(Country::getPop).sum();
}
public static class Country {
private String conti;
private int popu;
public Country(String conti, int popu) {
this.conti = conti;
this.popu = popu;
}
public String getContinent() {
return conti;
}
public void setContinent(String conti) {
this.conti = conti;
}
public int getPop() {
return popu;
}
public void setPop(int popu) {
this.popu = popu;
}
}
}
Comments
Leave a comment