0

I have a list which contains all setters of my POJO class.

public static void main(String[] args) throws Exception {

    Method[] publicMethods = SampleClass.class.getMethods();
    List<Method> setters = new ArrayList<>();

    for (Method method : publicMethods){
        if (method.getName().startsWith("set") && method.getParameterCount() == 1) {
            setters.add(method);
        }
    }
}

In documentation order of Method list is not guaranteed. My question is how can i sort my list of setters alphabetically?

  • 1
    Google for "how to sort objects in Java", click on one of the thousands of links you get, and read. – JB Nizet Aug 15 '17 at 13:03

2 Answers2

2

You need a custom comparator:

Collections.sort(setters, new Comparator<Method> {
  @Override
  public int compare(Method a, Method b) {
    return a.getName().compareTo(b.getName());
  }
});
Thomas
  • 174,939
  • 50
  • 355
  • 478
0

You can do that this way using java8 :

List<Method> setters = Arrays.asList( SampleClass.class.getMethods() )
.stream()
.filter(
  e->e.getName().startsWith("set")
).sorted(
  (a, b)->
        a.getName()
        .compareTo(b.getName())
).collect(Collectors.toList())
Vivick
  • 3,434
  • 2
  • 12
  • 25