Method getContinent() expects a String as an argument which can have three possible values: "Africa", "Asia" and "Europe".
Depending on the given value I get, I have to match the appropriate enum and get a list of all its values (as String).
There are repetitions in my code.
Is there a better way to do it?
Is it a good idea to place this in each of the enum's?:
Stream.of(CountryAsia.values())
.map(country -> country.getName())
.collect(Collectors.toList());
My code
Main class:
public class Main {
public static void main(String[] args) {
String continent = getContinent() //one of three possible values: "Africa" or "Asia" or "Europe"
List<String> list = null;
switch(continent) {
case "Africa":
list = Stream.of(CountryAfrica.values())
.map(country -> country.getName())
.collect(Collectors.toList());
break;
case "Asia":
list = Stream.of(CountryAsia.values())
.map(country -> country.getName())
.collect(Collectors.toList());
break;
case "Europe":
list = Stream.of(CountryEurope.values())
.map(country -> country.getName())
.collect(Collectors.toList());
break;
}
System.out.println(list);
//next instructions..
}
}
CountryEurope enum:
public enum CountryEurope {
DENMARK("Denmark"),
ESTONIA("Estonia"),
ICELAND("Iceland");
CountryEurope(String name) {
this.name = name;
}
private final String name;
public String getName() {
return name;
}
}
CountryAsia enum:
public enum CountryAsia {
AFGHANISTAN("Afghanistan"),
KAZAKHSTAN("Kazakhstan"),
UNITED_ARAB_EMIRATES("United Arab Emirates"),
UZBEKISTAN("Uzbekistan");
CountryAsia(String name) {
this.name = name;
}
private final String name;
public String getName() {
return name;
}
}
CountryAfrica class:
public enum CountryAfrica {
ALGIERIA("Algeria"),
WESTERN_SAHARA("Western Sahara"),
EGYPT("Egypt");
CountryAfrica(String name) {
this.name = name;
}
private final String name;
public String getName() {
return name;
}
}