fork download
  1.  
  2. import java.util.Comparator;
  3. import java.util.Optional;
  4.  
  5. public class Main {
  6.  
  7. public static void main(String[] args) {
  8.  
  9. SampleHeroes heroes = new SampleHeroes(
  10. new Hero("鈴木", 10),
  11. new Hero("佐藤", 30),
  12. new Hero("斎藤", 20)
  13. );
  14.  
  15. Optional<Hero> hopt = heroes.stream().max((x,y)->x.hp-y.hp);
  16.  
  17. if(hopt.isPresent()) {
  18. System.out.println("最大HPの勇者は" + hopt.get().name);
  19. }
  20. }
  21. }
  22.  
  23. //
  24. // ほんとはきっと java.util.List<Hero>
  25. //
  26. class SampleHeroes {
  27.  
  28. private final Hero[] heroes;
  29.  
  30. public SampleHeroes(Hero... heroes) {
  31.  
  32. this.heroes = heroes;
  33. }
  34.  
  35. //
  36. // heroes.stream()
  37. //
  38. SampleStream stream() {
  39.  
  40. return new SampleStream(heroes);
  41. }
  42. }
  43.  
  44. //
  45. // ほんとはきっと java.util.stream.Stream<Hero>
  46. //
  47. class SampleStream {
  48.  
  49. private final Hero[] heroes;
  50.  
  51. SampleStream(Hero[] heroes) {
  52.  
  53. this.heroes = heroes;
  54. }
  55.  
  56. //
  57. // heroes.stream().max()
  58. //
  59. public Optional<Hero> max(Comparator<Hero> comp) {
  60.  
  61. Hero max = heroes[0];
  62.  
  63. for (int i = 1; i < heroes.length; i ++) {
  64.  
  65. // (x,y) -> x.hp - y.hp で大小比較
  66. if (comp.compare(heroes[i], max) > 0) {
  67. max = heroes[i];
  68. }
  69. }
  70.  
  71. return Optional.of(max);
  72. }
  73. }
  74.  
  75. class Hero {
  76.  
  77. final String name;
  78. final int hp;
  79.  
  80. Hero(String name, int hp) {
  81.  
  82. this.name = name;
  83. this.hp = hp;
  84. }
  85. }
  86.  
Success #stdin #stdout 0.17s 57468KB
stdin
Standard input is empty
stdout
最大HPの勇者は佐藤