Skip to content

Instantly share code, notes, and snippets.

@Nkzn
Last active February 16, 2018 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nkzn/3ca811007c970111c2bce8bc6cf9bf83 to your computer and use it in GitHub Desktop.
Save Nkzn/3ca811007c970111c2bce8bc6cf9bf83 to your computer and use it in GitHub Desktop.
Java 8のStream APIでソートを実装する
import java.util.List;
import java.util.stream.Collectors;
import static java.util.Comparator.comparing;
public class Library {
public List<Model> sortWithName(List<Model> models) {
return models.stream() // このmodelsの中身は変更されない
.sorted(comparing(model -> model.name)) // 適当に降順ソート
.collect(Collectors.toList()); // このときに新しいList<Model>型コレクションが生成される
}
}
import spock.lang.Specification
class LibraryTest extends Specification {
def "sortWithName success"() {
setup:
def lib = new Library()
def models = [
new Model(24, "Nougat"),
new Model(11, "Honeycomb"),
new Model(8, "Eclair"),
new Model(19, "KitKat"),
new Model(4, "Cupcake"),
]
when:
def result = lib.sortWithName(models)
then:
result == [
new Model(4, "Cupcake"),
new Model(8, "Eclair"),
new Model(11, "Honeycomb"),
new Model(19, "KitKat"),
new Model(24, "Nougat"),
]
}
}
import java.util.Objects;
public class Model {
public final int id;
public final String name;
public Model(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Model model = (Model) o;
return id == model.id &&
Objects.equals(name, model.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment