0

I want to sort childRequirementGroupControllers which is a list of RequirementGroupController, but it is not allowing me to do. Syntactically, what am I doing wrong?

private List<RequirementGroupController> childRequirementGroupControllers = new ArrayList<RequirementGroupController>();

@Override
public void requirementAdded(Requirement requirement)
{   
    Collections.sort(childRequirementGroupControllers, (RequirementGroupController a1,
                    RequirementGroupController a2) -> a1.getRequirementGroup.getName() - a2.getRequirementGroup.getName());
}

Inside RequirementGroup Controller I have:

public class RequirementGroupController extends BaseController
{
  public Requirement getRequirementGroup()
  {
    return requirementGroup;
  }

}

Which contains a Requirement class and I finally want to sort by Requirement.getName().

lakeIn231
  • 1,177
  • 3
  • 14
  • 34

2 Answers2

2

You'll need to use String#compareTo to sort the object within the ArrayList by their names.

Collections.sort(childRequirementGroupControllers, (a1, a2) -> a1.getRequirementGroup.getName().compareTo(a2.getRequirementGroup.getName()));

note that I didn't explicitly specify the argument types when using the lambda expression as this is inferred from the context.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
1

You cannot subtract a String from another. A proper way to do it with Java 8 would be the following:

Collections.sort(childRequirementGroupControllers, Comparator.comparing(c -> c.getRequirementGroup.getName()));
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • When I try this it's saying "The type RequirementGroupController does not define getName(T) that is applicable here" – lakeIn231 May 17 '17 at 17:03
  • My apologies, I didn't see that `RequirementGroupController` did not implement a `getName` method. I'd use @Aominè's answer – Jacob G. May 17 '17 at 17:05
  • You can still use `Comparator.comparing(controller -> controller.getRequirementGroup().getName())` – James_D May 17 '17 at 17:05