Use List Sort

Properties

Property Value
First seen in jSparrow version 3.6.0
Minimum Java version 8
Remediation cost 2 min

Description

Replace static invocations of Collections.sort(List, Comparator) with List.sort(Comparator).

Benefits

Improves the readability by utilizing the Java 8 extensions of the List API.

Requirement & Tags

Requirements

Java 8

Code Changes

Static Sort Invocation

Pre

	public void sortUsersById(List<User> users) {
		Collections.sort(users, (User o1, User o2) -> o1.getId() - o2.getId());
	}

Post

	public void sortUsersById(List<User> users) {
		users.sort((User o1, User o2) -> o1.getId() - o2.getId());
	}

Inline Comparator Implementation

Pre

public void sortUsersById(List<User> users) {
	Collections.sort(users, new Comparator<User>() {
		@Override
		public int compare(User o1, User o2) {
			return o1.getId() - o2.getId();
		}
	});
}

Post

public void sortUsersById(List<User> users) {
	users.sort(new Comparator<User>() {
		@Override
		public int compare(User o1, User o2) {
			return o1.getId() - o2.getId();
		}
	});
}

Comparator Reference

Pre

public void sortUsersById(List<User> users) {
	Comparator<User> comparator = (User o1, User o2) -> o1.getId() - o2.getId();
	Collections.sort(users, comparator);
}

Post

public void sortUsersById(List<User> users) {
	Comparator<User> comparator = (User o1, User o2) -> o1.getId() - o2.getId();
	users.sort(comparator);
}

Automatic Application of This Rule

The automatic application of this rule is supported in the following jSparrow version: