我从库里查出来的集合是这样的放到一个list中
之前已经经过很复杂的查询,经过一系列处理这已经是其中的一部分id type name
1 1 xxxxx
2 1 xxxxx
3 1 xxxxx
4 1 xxxxx
5 2 xxxxx
6 3 xxxxx
7 4 xxxxx
8 2 xxxxx
9 3 xxxxx 要求输出 : 1,1,xxxxx ¦ 2,1,xxxxx ¦ 3,1,xxxxx ¦ 4,1,xxxxx 5,2,xxxxx ¦ 8,2,xxxxx 6,3,xxxxx ¦ 9,3,xxxxx 7,4,xxxxx
之前已经经过很复杂的查询,经过一系列处理这已经是其中的一部分id type name
1 1 xxxxx
2 1 xxxxx
3 1 xxxxx
4 1 xxxxx
5 2 xxxxx
6 3 xxxxx
7 4 xxxxx
8 2 xxxxx
9 3 xxxxx 要求输出 : 1,1,xxxxx ¦ 2,1,xxxxx ¦ 3,1,xxxxx ¦ 4,1,xxxxx 5,2,xxxxx ¦ 8,2,xxxxx 6,3,xxxxx ¦ 9,3,xxxxx 7,4,xxxxx
public void showYourObject(List<YourObject> list){
this.sortByType(list);
StringBuilder sb = new StringBuilder();
YourObject oldObj = null;
for(int i=0;i<list.size();i++) {
YourObject curObj = list.get(i);
if(i==0) {
oldObj = curObj;
}
if(curObj.getType()!=oldObj.getType()) {//不同了,加回车
if(sb.toString().endsWith("|")) sb.deleteCharAt(sb.length()-1);
sb.append("\n");
oldObj = curObj;
}
sb.append(curObj.getId()+",").append(curObj.getType()+",").append(curObj.getName()).append("|");
if(i==list.size()-1) {
if(sb.toString().endsWith("|")) sb.deleteCharAt(sb.length()-1);
}
}
System.out.println(sb.toString());
} private void sortByType(List<YourObject> list) {
Collections.sort(list, new Comparator<YourObject>() { public int compare(YourObject o1, YourObject o2) {
return o1.getType()>o2.getType()?1:0;
}
});
} public static void main(String[] args) {
List<YourObject> list = new ArrayList<YourObject>();
YourObject o1 = new YourObject(1,1,"object1");
YourObject o2 = new YourObject(2,1,"object2");
YourObject o3 = new YourObject(3,1,"object3");
YourObject o4 = new YourObject(4,1,"object4");
YourObject o5 = new YourObject(5,2,"object5");
YourObject o6 = new YourObject(6,3,"object6");
YourObject o7 = new YourObject(7,4,"object7");
YourObject o8 = new YourObject(8,2,"object8");
YourObject o9 = new YourObject(9,3,"object9");
list.add(o1);list.add(o2);list.add(o3);
list.add(o4);list.add(o5);list.add(o6);
list.add(o7);list.add(o8);list.add(o9);
ListSort listSort = new ListSort();
listSort.showYourObject(list); } public static class YourObject {
int id;
int type;
String name;
public YourObject(int id, int type, String name) {
super();
this.id = id;
this.type = type;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
我默认理解这个list存的是有id type name属性的对象,那么:temp = list.get(0).getType;
for(obj o : list){
if(temp!=o.getType){
system.out.println(...);
}else{
system.out.print(...+"|");
}}