好用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写法时),可以在这里留言我们一起讨论学习下。

 

posted @ 2013-01-09 23:24  海鸟  阅读(3247)  评论(0编辑  收藏  举报