avatar
swap specific item to the top in Array List Java

Imagine you have a POJO class representing an object called `Country`.

class Country {
    private String countryName;
    private String countryCode;

    public Country(String countryName, String countryCode) {
        this.countryName = countryName;
        this.countryCode = countryCode;
    }

    public String getCountryName() {
        return countryName;
    }

    public String getCountryCode() {
        return countryCode;
    }
}

Next, initialize the input Array List of `Country` objects as follows:

ArrayList<Country> countries = new ArrayList<>();
countries.add(new Country("Australia", "+61"));
countries.add(new Country("United States", "+1"));
countries.add(new Country("Canada", "+1"));
countries.add(new Country("United Kingdom", "+44"));

As you can see, the list is currently sorted alphabetically by country name. However, we want to move entries with the country code `+1` to the top of the list.

Comparator<CountryPhoneItem> countryCodeComparator = (c1, c2) -> {
    if (c1.getCountryCode().equals("+1")) {
        return -1;
    } else if (c2.getCountryCode().equals("+1")) {
        return 1;
    }
    return 0;
};

phoneItemList.sort(countryCodeComparator);
You need to login to do this manipulation!