作成 2003/2/14
JDKのCollectionsAPIの拡張です。 より高速なListやMapの実装や、便利なインターフェイス、クラス が提供されています。
ざっと見ただけですが、いくつか面白そうなクラスを 使ってみました。
| Interface | method | |
|---|---|---|
| Factory | Object create() | 作る |
| Predicate | boolean evaluate(Object input) | 判定する |
| Closure | void execute(Object input) | 実行する |
| Transformer | Object transform(Object input) | 変換する |
これらのインターフェイスと CollectionUtilsクラスを使って、 一括実行、一括変換、判定して一部取得 なんてことが可能です。
以下はTransformerとCollectionUtils#transform(2) を使った一括変換例です。
import java.util.Collection;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.FastArrayList;
import org.apache.commons.collections.Transformer;
public class Test1 {
public static void main(String[] args) {
Collection col = new FastArrayList();
col.add(new Man("いい"));
col.add(new Man("早起き"));
col.add(new Man("におう"));
System.out.println(col);
CollectionUtils.transform(col, new Man2WomanTransformer());
System.out.println(col);
}
}
class Man{
private String epithet;
private boolean isMale;
public Man(String epithet){
this.epithet = epithet;
this.isMale = true;
}
public void changeSex(){
isMale = !isMale;
}
public String toString(){
return epithet + (isMale ? "男" : "女");
}
}
class Man2WomanTransformer implements Transformer{
public Object transform(Object input) {
Man man = (Man)input;
man.changeSex();
return man;
}
}
実行結果です。男インスタンスの集合が一括変換(性転換?)され 女インスタンスの集合になりました。
FastArrayList[[いい男, 早起き男, におう男]] FastArrayList[[いい女, 早起き女, におう女]]
java.util.Propertiesの拡張クラスです。 何気にいろいろ出来て便利みたいです。
こういうプロパティーファイルから
today=St. Valentine’s Day 今日=バレンタインデー 王=18 3biki=殿様,千石,たこ sazaesan=サザエ sazaesan=ナミヘイ sazaesan=ウミエイ sazaesan=フネ
こんな感じで値を取得できます。
import java.util.Arrays;
import org.apache.commons.collections.ExtendedProperties;
public class Test2 {
public static void main(String[] args) throws Exception{
ExtendedProperties prop = new ExtendedProperties();
prop.load(Test2.class.getResourceAsStream("hoge.properties"));
System.out.println(prop);
//日本語key&valueOK
System.out.println(prop.getProperty("今日"));
//キーの値の型を指定するメソッドいろいろ
int n1 = prop.getInt("王");
System.out.println(n1);
//カンマ区切りで配列
String[] s1 = prop.getStringArray("3biki");
System.out.println(Arrays.asList(s1));
//並べて書いても配列
String[] s2 = prop.getStringArray("sazaesan");
System.out.println(Arrays.asList(s2));
}
}
実行結果
{today=St. Valentine’s Day, sazaesan=[サザエ, ナミヘイ, ウミエイ, フネ], 3biki=[殿様, 千石, たこ], 今日=バレンタインデー, 王=18}
バレンタインデー
18
[殿様, 千石, たこ]
[サザエ, ナミヘイ, ウミエイ, フネ]
Mobster
Jakarta Commonsを使ってスキルアップ