SweSnow
SweSnow

Reputation: 17374

Sorting list in alphabetical order

Im working on an application where I create a list with the installed apps and let the user select one. I've got everything working except for one thing; ordering them in alphabetical order. Here's the code I'm using:

private List<App> loadInstalledApps(boolean includeSysApps) {
  List<App> apps = new ArrayList<App>();

  PackageManager packageManager = getPackageManager();

  List<PackageInfo> packs = packageManager.getInstalledPackages(0); 

  for(int i=0; i < packs.size(); i++) {
     PackageInfo p = packs.get(i);

     App app = new App();
     app.setTitle(p.applicationInfo.loadLabel(packageManager).toString());
     app.setPackageName(p.packageName);
     app.setVersionName(p.versionName);
     app.setVersionCode(p.versionCode);
     CharSequence description = p.applicationInfo.loadDescription(packageManager);
     app.setDescription(description != null ? description.toString() : "");
     apps.add(app);
  }

  return apps;

}

Any help is appreciated!

Upvotes: 3

Views: 6292

Answers (4)

Waheed Nazir
Waheed Nazir

Reputation: 614

In Kotlin using lambda expression and comparator. you can easily sort your list alphabetically.

yourList.sortWith(Comparator { obj1, obj2 ->

 obj1.name.compareTo(obj2?.name!!, ignoreCase = true)

 })

Note: Here obj1 and obj2 is Model object of your list. e.g

val yourList: MutableList<Model> = ArrayList()

Upvotes: 0

loic .B
loic .B

Reputation: 298

Simpliest solution

Collections.sort(familleList, (famille, t1) -> famille.compareTo(t1));

Upvotes: 0

Samir Mangroliya
Samir Mangroliya

Reputation: 40426

Use Comparator to sort data ...

Collections.sort(apps, new Comparator<App>() {

                @Override
                public int compare(App lhs, App rhs) {
                         //here getTitle() method return app name...
                    return lhs.getTitle().compareTo(rhs.getTitle());

                }
            });

Upvotes: 11

moskis
moskis

Reputation: 1156

First: create comparator

Public class App implements Comparable {

// Lista de atributos y métodos

public int compareTo(Object o) {
    // logic of comparation
    return result; //must be integer
}

}

For example:

public int compareTo(Object o) {
        Direccion dir = (Direccion)o;
        if(this.name < app.getName())
            return -1;
        else if(this.name == app.getName())
            return 0;
        else
            return 1;
}

And when you want to short, use Collections.short(list)

Upvotes: 2

Related Questions