Apache Collections を使ってCollectionから指定したCollectionを抜き出す
Apache Collecionsには Collectionを操作する便利なユーティリティが沢山あります。
例えば、Listの中から指定したListだけ抜き出したい場合。
package sample; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.collections.Predicate; /** * @author suusuke * */ public class CollectionsSample { public static void main(String[] args) { new CollectionsSample().execute(); } private void execute() { List<Child> children = new ArrayList<Child>(); children.add(new Child("1")); children.add(new Child("2")); children.add(new Child("3")); children.add(new Child("4")); Parent parent1 = new Parent("1", children); // Listから指定したkeyで取得 List<Child> selectKey = getChildrenByKey(parent1.children, "1"); for (Child child : selectKey) { System.out.println(child.name); } System.out.println("----------------------"); // Listから指定した複数のkeyで取得 List<Child> selectKeys = getChildrenByKeys(parent1.children, "3", "4"); for (Child child : selectKeys) { System.out.println(child.name); } } /** * @param children * @param key * @return */ @SuppressWarnings("unchecked") private List<Child> getChildrenByKey(List<Child> children, final String key) { return (List<Child>) CollectionUtils.select(children, new Predicate() { @Override public boolean evaluate(Object input) { return key.equals(((Child) input).name); } }); } /** * @param children * @param keys * @return */ @SuppressWarnings("unchecked") private List<Child> getChildrenByKeys(List<Child> children, final String... keys) { return (List<Child>) CollectionUtils.select(children, new Predicate() { @Override public boolean evaluate(Object input) { boolean isEquals = false; for (String key : keys) { if (key.equals(((Child) input).name)) { isEquals = true; break; } } return isEquals; } }); } /** * @author suusuke * */ public class Parent { String name; List<Child> children; public Parent(String name, List<Child> children) { super(); this.name = name; this.children = children; } } /** * @author suusuke * */ public class Child { String name; public Child(String name) { super(); this.name = name; } } }
みたいに書いとくと、指定した条件でListが取得できます。
また、evaluateメソッドの実装を変えることで柔軟な条件を記述できるので、便利だと思います。
他にも、Apache Collections には Collection の和集合を返す、unionメソッドや、積集合を返す、intersectionメソッドがあるのでCollectionの操作するときは、Apache Collections で簡単にできないかどうか調べてみるのも良いんじゃないかと思います。