Last active
February 16, 2018 12:32
-
-
Save Nkzn/3ca811007c970111c2bce8bc6cf9bf83 to your computer and use it in GitHub Desktop.
Java 8のStream APIでソートを実装する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>型コレクションが生成される | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"), | |
] | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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