好用java庫(二) : lambdaj (集合操作)


接着介紹另外一個好用的java庫。

記得之前做過一個web services,業務邏輯是很簡單,可是代碼寫得多又長,因為基本上都是在對ArrayList結果進行各種篩選,排序,聚合等操作。大家都有這樣的感覺,這樣的代碼寫起來洋洋灑灑不覺得累,反正都是集合的循環操作不用動腦子,邊看着微博邊寫代碼都行,可是看的人就苦逼了,大循環嵌套小循環,半天找不到一句有用的「業務」描述性提示,你還不得不細心着看半天才知道原來是對集合做一些簡單操作。

lambdaJ 就是這樣的針對這樣的一個編程上下文場景而出來的,懶惰的聰明人最可能會寫出一個個好用的工具(說到「工具」,今天買了本「打造Facebook」,里面就提到了facebook公司的工具文化)來。

The best way to understand what lambdaj does and how it works is to start asking why we felt the need to develop it:

  • We were on a project with a complex data model
  • The biggest part of our business logic did almost always the same: iterating over collections of our business objects in order to do the same set of tasks
  • Loops (especially when nested or mixed with conditions) are harder to be read than to be written
  • We wanted to write our business logic in a less technical and closer to business fashion

--在javaone 2010會議上,lambdJ演講中PPT描述為什么lambdJ會開發出來

「我希望我們寫的代碼能讓業務員都能看懂」,我是這樣理解上面引用表達的內容的。

lambdJ提供了一個DSL的語法去對集合進行相關操作。DSL 就是 Domain specific Language,精髓在「Domain」一詞,「領域業務專門語言」,就是特定一個業務領域所專有的語言形式。比如我們所熟悉的SQL語言,就是一門DSL語言,它是專門針對數據庫操作的語言。那lambdJ就是一個專門針對「集合」操作的DSL語言。

下面我們就要看下如果使用它:

我們先定義一個類,它將會被我們要操作的集合對象包含。

public class Person implements Serializable{
    private static final long serialVersionUID = -5626560607865508210L;

    private int id;
    private String name;
    private int age;
}

//初始化一個集體對象
List<Person> persons = new ArrayList<Person>();
        
Person p = new Person();
p.setId(1);
p.setName("張三");
p.setAge(28);
persons.add(p);
p = new Person();
p.setId(2);
p.setName("李四");
p.setAge(35);
persons.add(p);

 joinFrom(連接字段)

String names = joinFrom(persons).getName();//output:張三, 李四

還可以自定義拼接符

String names = joinFrom(persons,"--").getName();//output: 張三--李四

select(條件選擇)

//篩選出年齡大於33歲的人
List<Person> ageGreaterThan33 = select(persons,having(on(Person.class).getAge(),Matchers.greaterThan(33)));

 selectMax,selectMin(最大/最小 對象)

Person personWithMaxAge = selectMax(persons, on(Person.class).getAge());//得到年齡最大的人

 

 max,min(最大/最小 對象屬性值)

int maxAge = max(persons, on(Person.class).getAge());//獲得集合中年齡最大的那個值

 

maxFrom,minFrom(和max,min功能一樣)

int maxAge = maxFrom(persons).getAge();//獲得集合中年齡最大的那個值,和上面的max一樣功能,形式不同而也

 

sum,sunFrom(求和)

int ageSum = sumFrom(persons).getAge();
int ageSum = sum(persons, on(Person.class).getAge());

 

sort(排序)

List<Person> sortByAge = sort(persons, on(Person.class).getAge());

 

extract(抽取字段屬性組成集合)

List<Integer> ageList = extract(persons, on(Person.class).getAge());

 

 index(以某字字段屬性為關鍵值分組)

Map<String,Person> mapByName = index(persons, on(Person.class).getName());

 

 

我這里寫的都是很簡單的例子,詳細的功能介紹請查看官網上的ppt。總之只有你想不到,沒有它做不到的集合操作功能。

還有,如果大家在工作中遇到很變態的集合操作而不知道怎么寫時(就像很復雜的sql寫法時),可以在這里留言我們一起討論學習下。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM