Java List根据对象的某个属性合并list

package com.test;

import java.util.ArrayList;
import java.util.List; public class FileTest {
public static void main(String[] args) {
List<FileBean> beans=new ArrayList<FileBean>();
FileBean bean1=new FileBean();
bean1.setDirectory("path1");
bean1.setSize(20);
beans.add(bean1);
FileBean bean2=new FileBean();
bean2.setDirectory("path1");
bean2.setSize(30);
beans.add(bean2);
FileBean bean3=new FileBean();
bean3.setDirectory("path1");
bean3.setSize(40);
beans.add(bean3);
FileBean bean4=new FileBean();
bean4.setDirectory("path2");
bean4.setSize(50);
beans.add(bean4);
FileBean bean5=new FileBean();
bean5.setDirectory("path2");
bean5.setSize(60);
beans.add(bean5);
FileBean bean6=new FileBean();
bean6.setDirectory("path3");
bean6.setSize(70);
beans.add(bean6);
FileBean bean7=new FileBean();
bean7.setDirectory("path3");
bean7.setSize(80);
beans.add(bean7);
FileBean bean8=new FileBean();
bean8.setDirectory("path3");
bean8.setSize(90);
beans.add(bean8);
List<FileBean> result = transferFilebean(beans);
System.out.println(result.size());
for(int i = 0; i< result.size();i++){
FileBean bean = result.get(i);
System.out.println(bean.getDirectory() + ";" + bean.getSize()); }
} public static List<FileBean> transferFilebean(List<FileBean> beans){
List<FileBean> result = new ArrayList<FileBean>(); if(beans == null){
return result;
}
for(int i = 0; i< beans.size();i++){
FileBean bean = beans.get(i);
if(!result.contains(bean)){
for(int j = i+1; j< beans.size();j++){
FileBean bean2 = beans.get(j);
if(bean.equals(bean2)){
bean.setSize(bean.getSize()+bean2.getSize());
}
}
result.add(bean);
}
}
return result;
} } class FileBean {
private String directory;
private long size;
private int dirNum;
public String getDirectory() {
return directory;
}
public void setDirectory(String directory) {
this.directory = directory;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
} public int getDirNum() {
return dirNum;
}
public void setDirNum(int dirNum) {
this.dirNum = dirNum;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((directory == null) ? 0 : directory.hashCode());
result = prime * result + (int) (size ^ (size >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
FileBean other = (FileBean) obj;
if (directory == null) {
if (other.directory != null)
return false;
} else if (!directory.equals(other.directory))
return false;
return true;
} }
上一篇:linux上安装redis的踩坑过程2


下一篇:部署mysql主从同步