Last active
November 22, 2016 07:33
-
-
Save gouf/0c79122226c356c04c18fb8c0099d6d8 to your computer and use it in GitHub Desktop.
同クラスの各インスタンスから、共通であるインスタンスメソッドを呼び出して、特定の結果を得る
This file contains hidden or 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.ArrayList; | |
import java.util.Arrays; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.stream.Stream; | |
import myClass.MyClass; | |
class Main { | |
public static void main(String []args) { | |
// 特定のクラスのインスタンスを想定 | |
MyClass button1 = new MyClass("Alice", false); | |
MyClass button2 = new MyClass("Ivan", true); | |
MyClass button3 = new MyClass("Bob", false); | |
// リストに格納 | |
List<MyClass> buttonList = Arrays.asList( | |
button1, | |
button2, | |
button3 | |
); | |
/* | |
* ここでリストを順次処理して | |
* 共通しているインスタンスのメソッドを呼び出す | |
* filter に合致する条件をもとに、そこからmap で当該要素の名前を得る | |
*/ | |
String resultName = buttonList.stream() | |
.filter((button) -> { | |
return button.isChecked(); | |
}) | |
.map((button) -> { | |
return button.getName(); | |
}) | |
.findFirst() | |
.get(); | |
System.out.println(resultName); // => "Ivan" | |
} | |
} |
This file contains hidden or 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
// ./myClass/MyClass.java | |
package myClass; | |
public class MyClass { | |
private Boolean checked; | |
private String name; | |
public Boolean isChecked() { | |
return checked; | |
} | |
public String getName() { | |
return this.name; | |
} | |
public MyClass(String _name, Boolean _checked) { | |
this.checked = _checked; | |
this.name = _name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment