Java集合分组


public class Data {

private Long id ;
private Long courseId ;
private String content ;

public Long getId() {
return id;
}

public Data setId(Long id) {
this.id = id;
return this ;
}

public Long getCourseId() {
return courseId;
}

public Data setCourseId(Long courseId) {
this.courseId = courseId;
return this ;
}

public String getContent() {
return content;
}

public Data setContent(String content) {
this.content = content;
return this ;
}

}



public class GroupTest {

/**
* 分組依據接口,用于集合分組時,獲取分組依據
* @author ZhangLiKun
* @title GroupBy
* @date 2013-4-23
*/
public interface GroupBy {
T groupby(Object obj) ;
}

/**
*
* @param colls
* @param gb
* @return
*/
public static final ,D> Map> group(Collection colls ,GroupBy gb){
if(colls == null || colls.isEmpty()) {
System.out.println("分組集合不能為空!");
return null ;
}
if(gb == null) {
System.out.println("分組依據接口不能為Null!");
return null ;
}
Iterator iter = colls.iterator() ;
Map> map = new HashMap>() ;
while(iter.hasNext()) {
D d = iter.next() ;
T t = gb.groupby(d) ;
if(map.containsKey(t)) {
map.get(t).add(d) ;
} else {
List list = new ArrayList() ;
list.add(d) ;
map.put(t, list) ;
}
}
return map ;
}


@Test
public void test() {
// 准备一个集合
final int loop = 1000 * 1000 ;
List list = new ArrayList () ; // size=8 * loop
for(int i = 0 ; i < loop ;i ++) {
list.add(new Data().setId(1L).setCourseId(200010L).setContent("AAA")) ;
list.add(new Data().setId(2L).setCourseId(200010L).setContent("BBB")) ;
list.add(new Data().setId(3L).setCourseId(200011L).setContent("CCC")) ;
list.add(new Data().setId(4L).setCourseId(200011L).setContent("DDD")) ;
list.add(new Data().setId(5L).setCourseId(200010L).setContent("EEE")) ;
list.add(new Data().setId(6L).setCourseId(200011L).setContent("FFF")) ;
list.add(new Data().setId(7L).setCourseId(200010L).setContent("GGG")) ;
list.add(new Data().setId(8L).setCourseId(200012L).setContent("HHH")) ;
}

// 进行分组
Map> map = group(list, new GroupBy() {
@Override
public Long groupby(Object obj) {
Data d = (Data)obj ;
return d.getCourseId() ; // 分组依据为课程ID
}
}) ;

Assert.assertEquals(3, map.size()) ;
Assert.assertEquals(4*loop, map.get(200010L).size()) ;
Assert.assertEquals(3*loop, map.get(200011L).size()) ;
Assert.assertEquals(1*loop, map.get(200012L).size()) ;
Assert.assertEquals("HHH", map.get(200012L).get(0).getContent()) ;

// 长度为8 * 1000 * 1000的集合测试用时:6481毫秒!

}

private long time ;

@Before
public void setup() {
time = System.currentTimeMillis() ;
}

@After
public void teardown() {
System.out.println(String.format("程序执行:%d毫秒!",System.currentTimeMillis() - time));
}

}

转自:https://my.oschina.net/zhanglikun/blog/124645

你可能感兴趣的:(J2EE,java)