# Replace Collection.sort with List.sort

# 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.

# Tags

# 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);
}

🛠️ Auto-refactor Available

You can auto-refactor this with jSparrow.
Drop this button to your Eclipse IDE workspace to install jSparrow for free:

Drag to your running Eclipse* workspace. *Requires Eclipse Marketplace Client

Need help? Check out our installation guide.

# Properties

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