Avoid Collections#sort

With the introduction of default methods in Java 8, Java finally grew a
List#sort method that can be used in place of the static
Collections#sort. Convert simple in-place sorts that need to be in-place
sorts to use this method where possible.

During the course of this change, it became obvious that many instances
of sort were just sorting a newly-created ArrayList in place. These can
be replaced with more idiomatic Stream constructions, sometimes even
eliminating a loop to populate the list.

One difference between List#sort and Collections#sort is there is no
List#sort() with no arguments; callers must always pass either
naturalOrder() or a null comparators. In this change, there were so few
remaining instances of sorting by natural order that typing
naturalOrder() didn't seem too repetitious, and it is quite readable.

Change-Id: I4d89421a72127e9a36cbd32aeac425c0471a1b3f
This commit is contained in:
Dave Borowitz 2018-08-31 13:26:57 -07:00
parent 7a06549cdf
commit 6724990a32
38 changed files with 130 additions and 146 deletions

View File

@ -32,7 +32,6 @@ import com.google.gwt.core.client.JsArrayString;
import com.google.gwtjsonrpc.client.impl.ser.JavaSqlTimestamp_JsonSerializer; import com.google.gwtjsonrpc.client.impl.ser.JavaSqlTimestamp_JsonSerializer;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -448,9 +447,8 @@ public class ChangeInfo extends JavaScriptObject {
public static void sortRevisionInfoByNumber(JsArray<RevisionInfo> list) { public static void sortRevisionInfoByNumber(JsArray<RevisionInfo> list) {
final int editParent = findEditParent(list); final int editParent = findEditParent(list);
Collections.sort( Natives.asList(list)
Natives.asList(list), .sort(comparing(r -> !r.isEdit() ? 2 * (r._number() - 1) + 1 : 2 * editParent));
comparing(r -> !r.isEdit() ? 2 * (r._number() - 1) + 1 : 2 * editParent));
} }
public static int findEditParent(JsArray<RevisionInfo> list) { public static int findEditParent(JsArray<RevisionInfo> list) {

View File

@ -19,7 +19,6 @@ import com.google.gerrit.common.data.FilenameComparator;
import com.google.gerrit.reviewdb.client.Patch; import com.google.gerrit.reviewdb.client.Patch;
import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArray;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
public class FileInfo extends JavaScriptObject { public class FileInfo extends JavaScriptObject {
@ -55,8 +54,7 @@ public class FileInfo extends JavaScriptObject {
public final native void _row(int r) /*-{ this._row = r }-*/; public final native void _row(int r) /*-{ this._row = r }-*/;
public static void sortFileInfoByPath(JsArray<FileInfo> list) { public static void sortFileInfoByPath(JsArray<FileInfo> list) {
Collections.sort( Natives.asList(list).sort(Comparator.comparing(FileInfo::path, FilenameComparator.INSTANCE));
Natives.asList(list), Comparator.comparing(FileInfo::path, FilenameComparator.INSTANCE));
} }
public static String getFileName(String path) { public static String getFileName(String path) {

View File

@ -14,11 +14,12 @@
package com.google.gerrit.client.rpc; package com.google.gerrit.client.rpc;
import static java.util.stream.Collectors.toCollection;
import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -57,10 +58,7 @@ public class NativeMap<T extends JavaScriptObject> extends JavaScriptObject {
} }
public final List<String> sortedKeys() { public final List<String> sortedKeys() {
Set<String> keys = keySet(); return keySet().stream().sorted().collect(toCollection(ArrayList::new));
List<String> sorted = new ArrayList<>(keys);
Collections.sort(sorted);
return sorted;
} }
public final native JsArray<T> values() /*-{ public final native JsArray<T> values() /*-{

View File

@ -42,7 +42,6 @@ import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwtexpui.clippy.client.CopyableLabel; import com.google.gwtexpui.clippy.client.CopyableLabel;
import com.google.gwtexpui.globalkey.client.NpTextArea; import com.google.gwtexpui.globalkey.client.NpTextArea;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
public class MyGpgKeysScreen extends SettingsScreen { public class MyGpgKeysScreen extends SettingsScreen {
@ -119,7 +118,7 @@ public class MyGpgKeysScreen extends SettingsScreen {
List<GpgKeyInfo> list = Natives.asList(result.values()); List<GpgKeyInfo> list = Natives.asList(result.values());
// TODO(dborowitz): Sort on something more meaningful, like // TODO(dborowitz): Sort on something more meaningful, like
// created date? // created date?
Collections.sort(list, comparing(GpgKeyInfo::id)); list.sort(comparing(GpgKeyInfo::id));
keys.clear(); keys.clear();
keyText.setText(""); keyText.setText("");
errorPanel.setVisible(false); errorPanel.setVisible(false);

View File

@ -14,6 +14,8 @@
package com.google.gerrit.client.account; package com.google.gerrit.client.account;
import static java.util.Comparator.naturalOrder;
import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.VoidResult; import com.google.gerrit.client.VoidResult;
import com.google.gerrit.client.rpc.GerritCallback; import com.google.gerrit.client.rpc.GerritCallback;
@ -29,7 +31,6 @@ import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -169,7 +170,7 @@ public class MyIdentitiesScreen extends SettingsScreen {
void display(JsArray<ExternalIdInfo> results) { void display(JsArray<ExternalIdInfo> results) {
List<ExternalIdInfo> idList = Natives.asList(results); List<ExternalIdInfo> idList = Natives.asList(results);
Collections.sort(idList); idList.sort(naturalOrder());
while (1 < table.getRowCount()) { while (1 < table.getRowCount()) {
table.removeRow(table.getRowCount() - 1); table.removeRow(table.getRowCount() - 1);

View File

@ -14,6 +14,8 @@
package com.google.gerrit.client.admin; package com.google.gerrit.client.admin;
import static java.util.stream.Collectors.toCollection;
import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.Gerrit;
import com.google.gerrit.common.data.AccessSection; import com.google.gerrit.common.data.AccessSection;
import com.google.gerrit.common.data.LabelType; import com.google.gerrit.common.data.LabelType;
@ -45,7 +47,6 @@ import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.ValueListBox; import com.google.gwt.user.client.ui.ValueListBox;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
public class AccessSectionEditor extends Composite public class AccessSectionEditor extends Composite
@ -205,9 +206,8 @@ public class AccessSectionEditor extends Composite
} }
private void sortPermissions(AccessSection accessSection) { private void sortPermissions(AccessSection accessSection) {
List<Permission> permissionList = new ArrayList<>(accessSection.getPermissions()); accessSection.setPermissions(
Collections.sort(permissionList); accessSection.getPermissions().stream().sorted().collect(toCollection(ArrayList::new)));
accessSection.setPermissions(permissionList);
} }
void setEditing(boolean editing) { void setEditing(boolean editing) {

View File

@ -34,7 +34,6 @@ import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.HTMLTable.Cell; import com.google.gwt.user.client.ui.HTMLTable.Cell;
import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Image;
import java.util.Collections;
import java.util.List; import java.util.List;
public class GroupTable extends NavigationTable<GroupInfo> { public class GroupTable extends NavigationTable<GroupInfo> {
@ -106,7 +105,7 @@ public class GroupTable extends NavigationTable<GroupInfo> {
table.removeRow(table.getRowCount() - 1); table.removeRow(table.getRowCount() - 1);
} }
Collections.sort(list, comparing(GroupInfo::name)); list.sort(comparing(GroupInfo::name));
for (GroupInfo group : list.subList(fromIndex, toIndex)) { for (GroupInfo group : list.subList(fromIndex, toIndex)) {
final int row = table.getRowCount(); final int row = table.getRowCount();
table.insertRow(row); table.insertRow(row);

View File

@ -14,6 +14,10 @@
package com.google.gerrit.client.change; package com.google.gerrit.client.change;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
import static java.util.stream.Collectors.toList;
import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.changes.ChangeApi; import com.google.gerrit.client.changes.ChangeApi;
import com.google.gerrit.client.changes.Util; import com.google.gerrit.client.changes.Util;
@ -135,9 +139,12 @@ class Labels extends Grid {
} }
void set(ChangeInfo info) { void set(ChangeInfo info) {
List<String> names = new ArrayList<>(info.labels()); List<String> names =
info.labels()
.stream()
.sorted()
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
Set<Integer> removable = info.removableReviewerIds(); Set<Integer> removable = info.removableReviewerIds();
Collections.sort(names);
resize(names.size(), 2); resize(names.size(), 2);
@ -197,8 +204,7 @@ class Labels extends Grid {
} }
private static List<Integer> sort(Set<Integer> keySet, int a, int b) { private static List<Integer> sort(Set<Integer> keySet, int a, int b) {
List<Integer> r = new ArrayList<>(keySet); List<Integer> r = keySet.stream().sorted().collect(toCollection(ArrayList::new));
Collections.sort(r);
if (keySet.contains(a)) { if (keySet.contains(a)) {
r.remove(Integer.valueOf(a)); r.remove(Integer.valueOf(a));
r.add(0, a); r.add(0, a);
@ -238,31 +244,32 @@ class Labels extends Grid {
Set<Integer> removable, Set<Integer> removable,
String label, String label,
Map<Integer, VotableInfo> votable) { Map<Integer, VotableInfo> votable) {
List<AccountInfo> users = new ArrayList<>(in); List<AccountInfo> users =
Collections.sort( in.stream()
users, .sorted(
new Comparator<AccountInfo>() { new Comparator<AccountInfo>() {
@Override @Override
public int compare(AccountInfo a, AccountInfo b) { public int compare(AccountInfo a, AccountInfo b) {
String as = name(a); String as = name(a);
String bs = name(b); String bs = name(b);
if (as.isEmpty()) { if (as.isEmpty()) {
return 1; return 1;
} else if (bs.isEmpty()) { } else if (bs.isEmpty()) {
return -1; return -1;
} }
return as.compareTo(bs); return as.compareTo(bs);
} }
private String name(AccountInfo a) { private String name(AccountInfo a) {
if (a.name() != null) { if (a.name() != null) {
return a.name(); return a.name();
} else if (a.email() != null) { } else if (a.email() != null) {
return a.email(); return a.email();
} }
return ""; return "";
} }
}); })
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
SafeHtmlBuilder html = new SafeHtmlBuilder(); SafeHtmlBuilder html = new SafeHtmlBuilder();
Iterator<? extends AccountInfo> itr = users.iterator(); Iterator<? extends AccountInfo> itr = users.iterator();

View File

@ -16,6 +16,8 @@ package com.google.gerrit.client.change;
import static com.google.gwt.event.dom.client.KeyCodes.KEY_ENTER; import static com.google.gwt.event.dom.client.KeyCodes.KEY_ENTER;
import static com.google.gwt.event.dom.client.KeyCodes.KEY_MAC_ENTER; import static com.google.gwt.event.dom.client.KeyCodes.KEY_MAC_ENTER;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toList;
import com.google.gerrit.client.Gerrit; import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.changes.ChangeApi; import com.google.gerrit.client.changes.ChangeApi;
@ -123,11 +125,15 @@ public class ReplyBox extends Composite {
this.lc = new LocalComments(project, psId.getParentKey()); this.lc = new LocalComments(project, psId.getParentKey());
initWidget(uiBinder.createAndBindUi(this)); initWidget(uiBinder.createAndBindUi(this));
List<String> names = new ArrayList<>(permitted.keySet()); List<String> names =
permitted
.keySet()
.stream()
.sorted()
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
if (names.isEmpty()) { if (names.isEmpty()) {
UIObject.setVisible(labelsParent, false); UIObject.setVisible(labelsParent, false);
} else { } else {
Collections.sort(names);
renderLabels(names, all, permitted); renderLabels(names, all, permitted);
} }
@ -439,8 +445,11 @@ public class ReplyBox extends Composite {
clp, project, psId, Util.C.commitMessage(), copyPath(Patch.MERGE_LIST, l))); clp, project, psId, Util.C.commitMessage(), copyPath(Patch.MERGE_LIST, l)));
} }
List<String> paths = new ArrayList<>(m.keySet()); List<String> paths =
Collections.sort(paths); m.keySet()
.stream()
.sorted()
.collect(collectingAndThen(toList(), Collections::unmodifiableList));
for (String path : paths) { for (String path : paths) {
if (!Patch.isMagic(path)) { if (!Patch.isMagic(path)) {

View File

@ -178,7 +178,7 @@ public class AccountDashboardScreen extends Screen implements ChangeListScreen {
} }
} }
Collections.sort(Natives.asList(out), outComparator()); Natives.asList(out).sort(outComparator());
table.updateColumnsForLabels(wip, out, in, done); table.updateColumnsForLabels(wip, out, in, done);
workInProgress.display(wip); workInProgress.display(wip);

View File

@ -27,7 +27,6 @@ import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Image;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -76,7 +75,7 @@ public class DashboardsTable extends NavigationTable<DashboardInfo> {
table.removeRow(table.getRowCount() - 1); table.removeRow(table.getRowCount() - 1);
} }
Collections.sort(list, comparing(DashboardInfo::id)); list.sort(comparing(DashboardInfo::id));
String ref = null; String ref = null;
for (DashboardInfo d : list) { for (DashboardInfo d : list) {

View File

@ -29,7 +29,6 @@ import com.google.gerrit.reviewdb.client.PatchSet;
import com.google.gerrit.reviewdb.client.Project; import com.google.gerrit.reviewdb.client.Project;
import com.google.gwt.core.client.JsArray; import com.google.gwt.core.client.JsArray;
import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.rpc.AsyncCallback;
import java.util.Collections;
/** Collection of published and draft comments loaded from the server. */ /** Collection of published and draft comments loaded from the server. */
class CommentsCollections { class CommentsCollections {
@ -159,7 +158,7 @@ class CommentsCollections {
for (CommentInfo c : Natives.asList(in)) { for (CommentInfo c : Natives.asList(in)) {
c.path(path); c.path(path);
} }
Collections.sort(Natives.asList(in), comparing(CommentInfo::updated)); Natives.asList(in).sort(comparing(CommentInfo::updated));
} }
return in; return in;
} }

View File

@ -22,7 +22,6 @@ import com.google.gerrit.client.projects.ProjectMap;
import com.google.gerrit.client.rpc.Natives; import com.google.gerrit.client.rpc.Natives;
import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter; import com.google.gwt.user.client.ui.FlexTable.FlexCellFormatter;
import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Image;
import java.util.Collections;
import java.util.List; import java.util.List;
public class ProjectsTable extends NavigationTable<ProjectInfo> { public class ProjectsTable extends NavigationTable<ProjectInfo> {
@ -70,7 +69,7 @@ public class ProjectsTable extends NavigationTable<ProjectInfo> {
} }
List<ProjectInfo> list = Natives.asList(projects.values()); List<ProjectInfo> list = Natives.asList(projects.values());
Collections.sort(list, comparing(ProjectInfo::name)); list.sort(comparing(ProjectInfo::name));
for (ProjectInfo p : list.subList(fromIndex, toIndex)) { for (ProjectInfo p : list.subList(fromIndex, toIndex)) {
insert(table.getRowCount(), p); insert(table.getRowCount(), p);
} }

View File

@ -23,7 +23,6 @@ import com.google.gwt.core.client.JsArray;
import com.google.gwt.core.client.JsArrayString; import com.google.gwt.core.client.JsArrayString;
import com.google.gwt.resources.client.DataResource; import com.google.gwt.resources.client.DataResource;
import com.google.gwt.safehtml.shared.SafeUri; import com.google.gwt.safehtml.shared.SafeUri;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -243,7 +242,7 @@ public class ModeInfo extends JavaScriptObject {
byMime.put(m.mode(), m); byMime.put(m.mode(), m);
} }
} }
Collections.sort(Natives.asList(filtered), comparing((ModeInfo m) -> m.name().toLowerCase())); Natives.asList(filtered).sort(comparing(m -> m.name().toLowerCase()));
setAll(filtered); setAll(filtered);
} }

View File

@ -456,8 +456,8 @@ class HttpPluginServlet extends HttpServlet implements StartPluginListener, Relo
} }
} }
Collections.sort(cmds, PluginEntry.COMPARATOR_BY_NAME); cmds.sort(PluginEntry.COMPARATOR_BY_NAME);
Collections.sort(docs, PluginEntry.COMPARATOR_BY_NAME); docs.sort(PluginEntry.COMPARATOR_BY_NAME);
StringBuilder md = new StringBuilder(); StringBuilder md = new StringBuilder();
md.append(String.format("# Plugin %s #\n", pluginName)); md.append(String.format("# Plugin %s #\n", pluginName));

View File

@ -15,6 +15,7 @@
package com.google.gerrit.index.query; package com.google.gerrit.index.query;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.base.Throwables; import com.google.common.base.Throwables;
import com.google.common.collect.FluentIterable; import com.google.common.collect.FluentIterable;
@ -26,7 +27,6 @@ import com.google.gwtorm.server.OrmRuntimeException;
import com.google.gwtorm.server.ResultSet; import com.google.gwtorm.server.ResultSet;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
@ -175,10 +175,8 @@ public class AndSource<T> extends AndPredicate<T>
return cardinality; return cardinality;
} }
private List<Predicate<T>> sort(Collection<? extends Predicate<T>> that) { private ImmutableList<Predicate<T>> sort(Collection<? extends Predicate<T>> that) {
List<Predicate<T>> r = new ArrayList<>(that); return that.stream().sorted(this).collect(toImmutableList());
Collections.sort(r, this);
return r;
} }
@Override @Override

View File

@ -30,7 +30,6 @@ import java.nio.file.Files;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.jar.Attributes; import java.util.jar.Attributes;
import java.util.jar.JarFile; import java.util.jar.JarFile;
@ -66,7 +65,7 @@ public class InitPlugins implements InitStep {
} }
result.add(new PluginData(pluginName, pluginVersion, tmpPlugin)); result.add(new PluginData(pluginName, pluginVersion, tmpPlugin));
}); });
Collections.sort(result, comparing(p -> p.name)); result.sort(comparing(p -> p.name));
return result; return result;
} }

View File

@ -502,7 +502,7 @@ public class CommentsUtil {
} }
private static <T extends Comment> List<T> sort(List<T> comments) { private static <T extends Comment> List<T> sort(List<T> comments) {
Collections.sort(comments, COMMENT_ORDER); comments.sort(COMMENT_ORDER);
return comments; return comments;
} }

View File

@ -34,7 +34,6 @@ import java.io.IOException;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Deque; import java.util.Deque;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
@ -110,7 +109,7 @@ public class WalkSorter {
for (Map.Entry<Project.NameKey, Collection<ChangeData>> e : byProject.asMap().entrySet()) { for (Map.Entry<Project.NameKey, Collection<ChangeData>> e : byProject.asMap().entrySet()) {
sortedByProject.add(sortProject(e.getKey(), e.getValue())); sortedByProject.add(sortProject(e.getKey(), e.getValue()));
} }
Collections.sort(sortedByProject, PROJECT_LIST_SORTER); sortedByProject.sort(PROJECT_LIST_SORTER);
return Iterables.concat(sortedByProject); return Iterables.concat(sortedByProject);
} }

View File

@ -73,7 +73,6 @@ import java.io.IOException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -329,10 +328,9 @@ public class EventFactory {
} }
} }
// Sort by original parent order. // Sort by original parent order.
Collections.sort( ca.dependsOn.sort(
ca.dependsOn,
comparing( comparing(
(DependencyAttribute d) -> { d -> {
for (int i = 0; i < parentNames.size(); i++) { for (int i = 0; i < parentNames.size(); i++) {
if (parentNames.get(i).equals(d.revision)) { if (parentNames.get(i).equals(d.revision)) {
return i; return i;

View File

@ -220,7 +220,7 @@ public class MergeUtil {
} catch (IOException e) { } catch (IOException e) {
throw new IntegrationException("Branch head sorting failed", e); throw new IntegrationException("Branch head sorting failed", e);
} }
Collections.sort(result, CodeReviewCommit.ORDER); result.sort(CodeReviewCommit.ORDER);
return result; return result;
} }

View File

@ -14,13 +14,15 @@
package com.google.gerrit.server.git.meta; package com.google.gerrit.server.git.meta;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.server.git.ValidationError; import com.google.gerrit.server.git.ValidationError;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -122,10 +124,8 @@ public class TabFile {
return buf.toString(); return buf.toString();
} }
protected static <T extends Comparable<? super T>> List<T> sort(Collection<T> m) { protected static <T extends Comparable<? super T>> ImmutableList<T> sort(Collection<T> m) {
ArrayList<T> r = new ArrayList<>(m); return m.stream().sorted().collect(toImmutableList());
Collections.sort(r);
return r;
} }
protected static String pad(int len, String src) { protected static String pad(int len, String src) {

View File

@ -239,7 +239,7 @@ public class CommentSender extends ReplyToChangeSender {
} }
} }
Collections.sort(groups, Comparator.comparing(g -> g.filename, FilenameComparator.INSTANCE)); groups.sort(Comparator.comparing(g -> g.filename, FilenameComparator.INSTANCE));
return groups; return groups;
} }

View File

@ -79,7 +79,6 @@ import java.nio.charset.Charset;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.text.ParseException; import java.text.ParseException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.HashSet; import java.util.HashSet;
@ -297,9 +296,7 @@ class ChangeNotesParser {
} }
result.put(a.getPatchSetId(), a); result.put(a.getPatchSetId(), a);
} }
for (Collection<PatchSetApproval> v : result.asMap().values()) { result.keySet().forEach(k -> result.get(k).sort(ChangeNotes.PSA_BY_TIME));
Collections.sort((List<PatchSetApproval>) v, ChangeNotes.PSA_BY_TIME);
}
return result; return result;
} }

View File

@ -15,10 +15,12 @@
package com.google.gerrit.server.notedb; package com.google.gerrit.server.notedb;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.gerrit.server.CommentsUtil.COMMENT_ORDER; import static com.google.gerrit.server.CommentsUtil.COMMENT_ORDER;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ListMultimap; import com.google.common.collect.ListMultimap;
import com.google.gerrit.reviewdb.client.Account; import com.google.gerrit.reviewdb.client.Account;
import com.google.gerrit.reviewdb.client.Comment; import com.google.gerrit.reviewdb.client.Comment;
@ -30,8 +32,6 @@ import java.io.OutputStream;
import java.io.OutputStreamWriter; import java.io.OutputStreamWriter;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import org.eclipse.jgit.lib.PersonIdent; import org.eclipse.jgit.lib.PersonIdent;
@ -87,8 +87,7 @@ public class LegacyChangeNoteWrite {
return; return;
} }
List<Integer> psIds = new ArrayList<>(comments.keySet()); ImmutableList<Integer> psIds = comments.keySet().stream().sorted().collect(toImmutableList());
Collections.sort(psIds);
OutputStreamWriter streamWriter = new OutputStreamWriter(out, UTF_8); OutputStreamWriter streamWriter = new OutputStreamWriter(out, UTF_8);
try (PrintWriter writer = new PrintWriter(streamWriter)) { try (PrintWriter writer = new PrintWriter(streamWriter)) {

View File

@ -19,7 +19,6 @@ import com.google.gerrit.reviewdb.client.Project;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted; import com.google.inject.assistedinject.Assisted;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
@ -66,8 +65,9 @@ public class DiffSummaryLoader implements Callable<DiffSummary> {
break; break;
} }
} }
Collections.sort(r);
return new DiffSummary( return new DiffSummary(
r.toArray(new String[r.size()]), patchList.getInsertions(), patchList.getDeletions()); r.stream().sorted().toArray(String[]::new),
patchList.getInsertions(),
patchList.getDeletions());
} }
} }

View File

@ -35,7 +35,6 @@ import eu.medsea.mimeutil.MimeType;
import eu.medsea.mimeutil.MimeUtil2; import eu.medsea.mimeutil.MimeUtil2;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -364,7 +363,7 @@ class PatchScriptBuilder {
// them correctly later. // them correctly later.
// //
edits.addAll(empty); edits.addAll(empty);
Collections.sort(edits, EDIT_SORT); edits.sort(EDIT_SORT);
} }
private void safeAdd(List<Edit> empty, Edit toAdd) { private void safeAdd(List<Edit> empty, Edit toAdd) {

View File

@ -26,7 +26,6 @@ import com.google.inject.Module;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import com.google.inject.name.Named; import com.google.inject.name.Named;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.IdentityHashMap; import java.util.IdentityHashMap;
import java.util.List; import java.util.List;
@ -88,7 +87,7 @@ public class SectionSortCache {
poison |= srcMap.put(sections.get(i), i) != null; poison |= srcMap.put(sections.get(i), i) != null;
} }
Collections.sort(sections, new MostSpecificComparator(ref)); sections.sort(new MostSpecificComparator(ref));
int[] srcIdx; int[] srcIdx;
if (isIdentityTransform(sections, srcMap)) { if (isIdentityTransform(sections, srcMap)) {

View File

@ -15,6 +15,7 @@
package com.google.gerrit.server.project; package com.google.gerrit.server.project;
import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.gerrit.common.data.Permission.isPermission; import static com.google.gerrit.common.data.Permission.isPermission;
import static com.google.gerrit.reviewdb.client.Project.DEFAULT_SUBMIT_TYPE; import static com.google.gerrit.reviewdb.client.Project.DEFAULT_SUBMIT_TYPE;
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.toList;
@ -1451,10 +1452,8 @@ public class ProjectConfig extends VersionedMetaData implements ValidationError.
validationErrors.add(error); validationErrors.add(error);
} }
private static <T extends Comparable<? super T>> List<T> sort(Collection<T> m) { private static <T extends Comparable<? super T>> ImmutableList<T> sort(Collection<T> m) {
ArrayList<T> r = new ArrayList<>(m); return m.stream().sorted().collect(toImmutableList());
Collections.sort(r);
return r;
} }
public boolean hasLegacyPermissions() { public boolean hasLegacyPermissions() {

View File

@ -37,7 +37,6 @@ import com.google.gerrit.server.account.AccountLoader;
import com.google.gerrit.server.permissions.PermissionBackendException; import com.google.gerrit.server.permissions.PermissionBackendException;
import com.google.inject.Inject; import com.google.inject.Inject;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.TreeMap; import java.util.TreeMap;
@ -98,9 +97,7 @@ class CommentJson {
list.add(o); list.add(o);
} }
for (List<T> list : out.values()) { out.values().forEach(l -> l.sort(COMMENT_INFO_ORDER));
Collections.sort(list, COMMENT_INFO_ORDER);
}
if (loader != null) { if (loader != null) {
loader.fill(); loader.fill();

View File

@ -14,6 +14,7 @@
package com.google.gerrit.server.restapi.change; package com.google.gerrit.server.restapi.change;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.extensions.common.CommentInfo; import com.google.gerrit.extensions.common.CommentInfo;
import com.google.gerrit.extensions.restapi.RestReadView; import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.Comment; import com.google.gerrit.reviewdb.client.Comment;
@ -61,7 +62,7 @@ public class ListRevisionDrafts implements RestReadView<RevisionResource> {
.format(listComments(rsrc)); .format(listComments(rsrc));
} }
public List<CommentInfo> getComments(RevisionResource rsrc) public ImmutableList<CommentInfo> getComments(RevisionResource rsrc)
throws OrmException, PermissionBackendException { throws OrmException, PermissionBackendException {
return commentJson return commentJson
.get() .get()

View File

@ -14,6 +14,7 @@
package com.google.gerrit.server.restapi.change; package com.google.gerrit.server.restapi.change;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.extensions.common.RobotCommentInfo; import com.google.gerrit.extensions.common.RobotCommentInfo;
import com.google.gerrit.extensions.restapi.RestReadView; import com.google.gerrit.extensions.restapi.RestReadView;
import com.google.gerrit.reviewdb.client.RobotComment; import com.google.gerrit.reviewdb.client.RobotComment;
@ -52,7 +53,7 @@ public class ListRobotComments implements RestReadView<RevisionResource> {
.format(listComments(rsrc)); .format(listComments(rsrc));
} }
public List<RobotCommentInfo> getComments(RevisionResource rsrc) public ImmutableList<RobotCommentInfo> getComments(RevisionResource rsrc)
throws OrmException, PermissionBackendException { throws OrmException, PermissionBackendException {
return commentJson return commentJson
.get() .get()

View File

@ -41,7 +41,6 @@ import com.google.inject.Inject;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.eclipse.jgit.errors.ConfigInvalidException; import org.eclipse.jgit.errors.ConfigInvalidException;
@ -138,7 +137,7 @@ public class GetAuditLog implements RestReadView<GroupResource> {
accountLoader.fill(); accountLoader.fill();
// sort by date and then reverse so that the newest audit event comes first // sort by date and then reverse so that the newest audit event comes first
Collections.sort(auditEvents, comparing((GroupAuditEventInfo a) -> a.date).reversed()); auditEvents.sort(comparing((GroupAuditEventInfo a) -> a.date).reversed());
return auditEvents; return auditEvents;
} }
} }

View File

@ -30,7 +30,6 @@ import com.google.gwtorm.server.OrmException;
import com.google.inject.Inject; import com.google.inject.Inject;
import com.google.inject.Singleton; import com.google.inject.Singleton;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
@Singleton @Singleton
@ -72,8 +71,7 @@ public class ListSubgroups implements RestReadView<GroupResource> {
continue; continue;
} }
} }
Collections.sort( included.sort(
included,
comparing((GroupInfo g) -> nullToEmpty(g.name)).thenComparing(g -> nullToEmpty(g.id))); comparing((GroupInfo g) -> nullToEmpty(g.name)).thenComparing(g -> nullToEmpty(g.id)));
return included; return included;
} }

View File

@ -46,7 +46,6 @@ import com.google.inject.Inject;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Set; import java.util.Set;
@ -226,7 +225,7 @@ public class ListBranches implements RestReadView<ProjectResource> {
// Do nothing. // Do nothing.
} }
} }
Collections.sort(branches, new BranchComparator()); branches.sort(new BranchComparator());
return branches; return branches;
} }

View File

@ -40,7 +40,6 @@ import com.google.inject.Inject;
import java.io.IOException; import java.io.IOException;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.eclipse.jgit.errors.RepositoryNotFoundException; import org.eclipse.jgit.errors.RepositoryNotFoundException;
@ -135,7 +134,7 @@ public class ListTags implements RestReadView<ProjectResource> {
} }
} }
Collections.sort(tags, comparing(t -> t.ref)); tags.sort(comparing(t -> t.ref));
return new RefFilter<TagInfo>(Constants.R_TAGS) return new RefFilter<TagInfo>(Constants.R_TAGS)
.start(start) .start(start)

View File

@ -53,7 +53,6 @@ import com.google.gerrit.server.update.RepoContext;
import com.google.gwtorm.server.OrmException; import com.google.gwtorm.server.OrmException;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -184,8 +183,7 @@ abstract class SubmitStrategyOp implements BatchUpdateOp {
continue; // Bogus ref, can't be merged into tip so we don't care. continue; // Bogus ref, can't be merged into tip so we don't care.
} }
} }
Collections.sort( commits.sort(
commits,
ReviewDbUtil.intKeyOrdering().reverse().onResultOf(CodeReviewCommit::getPatchsetId)); ReviewDbUtil.intKeyOrdering().reverse().onResultOf(CodeReviewCommit::getPatchsetId));
CodeReviewCommit result = MergeUtil.findAnyMergedInto(rw, commits, tip); CodeReviewCommit result = MergeUtil.findAnyMergedInto(rw, commits, tip);
if (result == null) { if (result == null) {

View File

@ -15,8 +15,10 @@
package com.google.gerrit.sshd.commands; package com.google.gerrit.sshd.commands;
import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.gerrit.sshd.CommandMetaData.Mode.MASTER_OR_SLAVE; import static com.google.gerrit.sshd.CommandMetaData.Mode.MASTER_OR_SLAVE;
import com.google.common.collect.ImmutableList;
import com.google.gerrit.common.TimeUtil; import com.google.gerrit.common.TimeUtil;
import com.google.gerrit.common.data.GlobalCapability; import com.google.gerrit.common.data.GlobalCapability;
import com.google.gerrit.extensions.annotations.RequiresCapability; import com.google.gerrit.extensions.annotations.RequiresCapability;
@ -33,11 +35,7 @@ import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
import java.net.SocketAddress; import java.net.SocketAddress;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Optional; import java.util.Optional;
import org.apache.sshd.common.io.IoAcceptor; import org.apache.sshd.common.io.IoAcceptor;
import org.apache.sshd.common.io.IoSession; import org.apache.sshd.common.io.IoSession;
@ -92,25 +90,27 @@ final class ShowConnections extends SshCommand {
throw new Failure(1, "fatal: sshd no longer running"); throw new Failure(1, "fatal: sshd no longer running");
} }
final List<IoSession> list = new ArrayList<>(acceptor.getManagedSessions().values()); final ImmutableList<IoSession> list =
Collections.sort( acceptor
list, .getManagedSessions()
new Comparator<IoSession>() { .values()
@Override .stream()
public int compare(IoSession arg0, IoSession arg1) { .sorted(
if (arg0 instanceof MinaSession) { (arg0, arg1) -> {
MinaSession mArg0 = (MinaSession) arg0; if (arg0 instanceof MinaSession) {
MinaSession mArg1 = (MinaSession) arg1; MinaSession mArg0 = (MinaSession) arg0;
if (mArg0.getSession().getCreationTime() < mArg1.getSession().getCreationTime()) { MinaSession mArg1 = (MinaSession) arg1;
return -1; if (mArg0.getSession().getCreationTime()
} else if (mArg0.getSession().getCreationTime() < mArg1.getSession().getCreationTime()) {
> mArg1.getSession().getCreationTime()) { return -1;
return 1; } else if (mArg0.getSession().getCreationTime()
} > mArg1.getSession().getCreationTime()) {
} return 1;
return (int) (arg0.getId() - arg1.getId()); }
} }
}); return (int) (arg0.getId() - arg1.getId());
})
.collect(toImmutableList());
hostNameWidth = wide ? Integer.MAX_VALUE : columns - 9 - 9 - 10 - 32; hostNameWidth = wide ? Integer.MAX_VALUE : columns - 9 - 9 - 10 - 32;