-
Notifications
You must be signed in to change notification settings - Fork 33
/
Problem_07.java
87 lines (76 loc) · 1.89 KB
/
Problem_07.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Cracking-The-Coding-Interview
* Problem_07.java
*/
package com.deepak.ctci.Ch13_Java;
import java.util.List;
/**
* <br> Problem Statement:
*
* There is a class country that has method
* getContinent() and getPopulation(). Write a function
* "int getPopulation(List<Country> countries, String continent)"
* that computes the total population of a given continent,
* given a list of all countries and the name of a continent.
*
* </br>
*
* @author Deepak
*/
public class Problem_07 {
/**
* Method to get population using advanced java loop
* @param countries
* @param continent
* @return {@link int}
*/
public static int getPopulationUsingLoop(List<Country> countries, String continent) {
int totalPopulation = 0;
for (Country country : countries) {
if (country.getContinent().equalsIgnoreCase(continent)) {
totalPopulation += country.getPopulation();
}
}
return totalPopulation;
}
/**
* Method to get population using java 8 lambdas
* @param countries
* @param continent
* @return {@link int}
*/
public static int getPopulationUsingLambda(List<Country> countries, String continent) {
return countries.stream().filter(country -> country.getContinent().equalsIgnoreCase(continent)).mapToInt(Country::getPopulation).sum();
}
/**
* Class country
*
* @author Deepak
*/
public static class Country {
private String continent;
private int population;
/**
* Constructor
*
* @param continent
* @param population
*/
public Country(String continent, int population) {
this.continent = continent;
this.population = population;
}
public String getContinent() {
return continent;
}
public void setContinent(String continent) {
this.continent = continent;
}
public int getPopulation() {
return population;
}
public void setPopulation(int population) {
this.population = population;
}
}
}