Last active
December 13, 2015 21:39
-
-
Save koji-k/4979202 to your computer and use it in GitHub Desktop.
GroovyでのSetの使い方と積集合の求め方のサンプル
Sample of Set on Groovy
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
/********************************** | |
* sample of Set | |
**********************************/ | |
import groovy.transform.EqualsAndHashCode | |
@EqualsAndHashCode | |
class sample { | |
def age | |
} | |
def list1 = [ | |
new sample(age:1), | |
new sample(age:1), | |
new sample(age:2), | |
] | |
def list2 = [ | |
new sample(age:2), | |
new sample(age:3), | |
new sample(age:4) | |
] | |
// ListからSetへの変換 | |
// convert to Set from List | |
def set1 = list1 as Set | |
def set2 = list2 as Set | |
assert [new sample(age:1),new sample(age:2)] as Set == set1 | |
assert [new sample(age:2),new sample(age:3),new sample(age:4)] as Set == set2 | |
// Setへの値の追加("set2.add(new sample(age:1))"は追加されません) | |
// add value to Set ("set2.add(new sample(age:1))" is not added) | |
set2.add(new sample(age:1)) | |
set2.add(new sample(age:5)) | |
set1.add(new sample(age:5)) | |
// 積集合の取得(つまり両方のSetに存在するオブジェクト) | |
// get objects that exists in both Set | |
def both = set1.intersect(set2) //or def both = set1.findAll{it in set2} | |
both.each{println it.age} // result is "1" and "2" and "5" | |
// 型はこんな感じ | |
// Type is so | |
assert "class java.util.ArrayList" == list1.getClass().toString() | |
assert "class java.util.LinkedHashSet" == set1.getClass().toString() | |
assert "class java.util.LinkedHashSet" == both.getClass().toString() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment