把一堆数据整理出来,根据value分类:
对象实体类
class="java" name="code">
public class TestObj {
private String title ;
private String value;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
伪Map类:
import java.util.List;
public class Wmap {
private String key;
private List<TestObj> value;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public List<TestObj> getValue() {
return value;
}
public void setValue(List<TestObj> value) {
this.value = value;
}
}
测试类:
import java.util.ArrayList;
import java.util.List;
public class Distinct {
public static void main(String[] args) {
// ------------------------------------------- 准备数据
TestObj tobj1 = new TestObj();
tobj1.setTitle("tttt");
tobj1.setValue("1");
TestObj tobj2 = new TestObj();
tobj2.setTitle("qqq");
tobj2.setValue("2");
TestObj tobj3 = new TestObj();
tobj3.setTitle("www");
tobj3.setValue("3");
List<TestObj> lo = new ArrayList<TestObj>();
lo.add(tobj1);
lo.add(tobj1);
lo.add(tobj1);
lo.add(tobj2);
lo.add(tobj2);
lo.add(tobj3);
// ------------------------------------------- 挑出value不同的对象
List<TestObj> lo2 = lo;
List<TestObj> lod = new ArrayList<TestObj>();
lod.add(lo2.get(0));
for (int a = 0; a < lo2.size(); a++) {
for (int b = 0, c = 0; b < lod.size(); b++) {
if (!lo2.get(a).getValue().equals(lod.get(b).getValue())) {
c++;
}
if (c == lod.size()) {
lod.add(lo2.get(a));
break;
}
}
}
System.out.println(lod.size());
// ------------------------------------------统一放进一个伪Map中,key是不同的值,value是list对象集合
List<Wmap> lm = new ArrayList<Wmap>();
// 初始化MAP
for (int d = 0; d < lod.size(); d++) {
Wmap wmap = new Wmap();
wmap.setKey(lod.get(d).getValue());
wmap.setValue(new ArrayList<TestObj>());
lm.add(wmap);
}
for (int e = 0; e < lod.size(); e++) {
for (int f = 0; f < lo2.size(); f++) {
if (lo2.get(f).getValue().equals(lod.get(e).getValue())) {
for(int g = 0 ; g <lm.size();g++ ){
if(lo2.get(f).getValue().equals(lm.get(g).getKey())){
lm.get(g).getValue().add(lo2.get(f));
}
}
}
}
}
System.out.println(lm);
}
}
感觉这个就是像把数据变成树,用不同的value变成节点。
写完之后,感觉这个太繁琐,感觉可以优化,直接拿出value进行比较动态生成,不用这么繁琐。。