🏗 Step 1: Define the Country Class
public class Country {
private
String countryCode;
private String countryName;
private
String continent;
//
Constructor
public
Country(String countryCode, String countryName, String continent) {
this.countryCode = countryCode;
this.countryName = countryName;
this.continent
= continent;
}
//
Getters
public
String getCountryCode() {
return countryCode;
}
public
String getCountryName() {
return countryName;
}
public
String getContinent() {
return continent;
}
@Override
public
String toString() {
return countryCode + " - " + countryName + " (" +
continent + ")";
}
}
🏗 Step 2: Sort and Collect Using
Java 8 Streams
import java.util.*;
import java.util.stream.Collectors;
public class CountrySortExample {
public
static void main(String[] args) {
List<Country> countries
= Arrays.asList(
new Country("IN", "India", "Asia"),
new Country("US", "United States", "North
America"),
new Country("FR", "France", "Europe"),
new Country("JP", "Japan", "Asia")
);
// ✅ Sort by countryName
List<Country> sortedList = countries.stream()
.sorted(Comparator.comparing(Country::getCountryName))
.collect(Collectors.toList());
System.out.println("Sorted Countries:");
sortedList.forEach(System.out::println);
// ✅ Collect unique country names into a Set
Set<String> countryNames = countries.stream()
.map(Country::getCountryName)
.collect(Collectors.toSet());
System.out.println("\nUnique Country Names:");
countryNames.forEach(System.out::println);
}
}
📊 Output Example
Sorted Countries:
FR - France (Europe)
IN - India (Asia)
JP - Japan (Asia)
US - United States (North America)
Unique Country Names:
France
India
Japan
United States
🔑 Key Points
- Comparator.comparing(Country::getCountryName) → sorts by countryName.
- .map(Country::getCountryName).collect(Collectors.toSet()) → extracts unique names.
- forEach(System.out::println) → prints results cleanly.
👉 Do you want me to also show how to sort by
multiple fields (e.g., first by continent, then by
countryName)? That’s a common real-world
requirement when dealing with hierarchical data like countries.
No comments:
Post a Comment