Wednesday, January 11, 2012

Sort by 2 properties

There is list of articles that needs to be sorted by zone and then by name

List<Article> listaArtikala = articleManager.findByFilter(filter);
// sortiraj artikle po zoni
Collections.sort(listaArtikala, new Comparator<Article>()
{
@Override
public int compare(Article o1, Article o2)
{
return o1.getZone().getMark().compareTo(o2.getZone().getMark());
}
});

// razdvoji po zoni aktikle
Map<String, List<Article>> map = new TreeMap<String, List<Article>>();
for (Article a : listaArtikala)
{
String mark = a.getZone().getMark();
List<Article> tempList = map.get(mark);
if (tempList == null)
{
tempList = new ArrayList<Article>();
map.put(mark, tempList);
}
tempList.add(a);
}
listaArtikala.clear();

// sortiraj po imenu artikla
for (String mark : map.keySet())
{
List<Article> tempList = map.get(mark);
Collections.sort(tempList, new Comparator<Article>()
{
@Override
public int compare(Article o1, Article o2)
{
return o1.getName().compareTo(o2.getName());
}
});
listaArtikala.addAll(tempList);
}

No comments:

Post a Comment