Alphabetically Sort a Java Collection based upon the 'toString' value of its member items

前端 未结 10 1478
心在旅途
心在旅途 2020-12-29 22:10

Assume I have a user defined Java class called Foo such as:

public class Foo 
{

    private String aField;

    @Override
    public String toString()
    {         


        
10条回答
  •  难免孤独
    2020-12-29 22:42

    Sort ArrayList on POJO int property (Ascending or Descending):

    Collections.sort(myPojoList, (a, b) -> a.getId() - b.getId()); //ASC
    Collections.sort(myPojoList, (a, b) -> b.getId() - a.getId()); //DESC
    
    //Alternatively use Integer.compare()
    Collections.sort(myPojoList, (a, b) -> Integer.compare(a.getId(), b.getId())); //ASC
    Collections.sort(myPojoList, (a, b) -> Integer.compare(b.getId(), a.getId())); //DESC
    

    Sort ArrayList on POJO String property:

    Collections.sort(myPojoList, (a, b) -> a.getName().compareTo(b.getName())); //ASC
    Collections.sort(myPojoList, (a, b) -> b.getName().compareTo(a.getName())); //DESC
    

    Sort ArrayList on POJO Boolean property:

    Collections.sort(myPojoList, (a, b) -> Boolean.compare(a.isMale(), b.isMale())); //ASC
    Collections.sort(myPojoList, (a, b) -> Boolean.compare(b.isMale(), a.isMale())); //DESC
    

    Extra: get distinct ArrayList

    myPojoList= new ArrayList<>(new LinkedHashSet<>(myPojoList)); //Distinct
    

提交回复
热议问题