我有以下代码块,我正在尝试使用java流进行转换。
for(Emp emp:empList){
if(combinedData.getOrg()==null){
combinedData.setOrg(emp.getCompany());
}
combinedData.addToList(emp.getWorkLog());
if(combinedData.getRawData()!=null){
combinedData.setRawData(combinedData.getRawData()+emp.getData());
}
else{
combinedData.setRawData(emp.getData());
}
}
我面临的挑战是,我只需要设置一个Org,还需要附加到现有的原始数据。我知道使用流减少行数很容易做到。
完整代码如下
public class Main {
public static void main(String[] args) {
List<Emp> empList = Arrays.asList(
new Emp("x1","as2112","a"),
new Emp("x1","as2122","b"),
new Emp("x1","as2422","c"),
new Emp("x1","as2423","d"));
CombinedData combinedData = new CombinedData();
for(Emp emp:empList){
if(combinedData.getOrg()==null){
combinedData.setOrg(emp.getCompany());
}
combinedData.addToList(emp.getWorkLog());
if(combinedData.getRawData()!=null){
combinedData.setRawData(combinedData.getRawData()+emp.getData());
}
else{
combinedData.setRawData(emp.getData());
}
}
}
}
class Emp{
private String company;
private String workLog;
private String data;
public Emp(
String company,
String workLog,
String data) {
this.company = company;
this.workLog = workLog;
this.data = data;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getWorkLog() {
return workLog;
}
public void setWorkLog(String workLog) {
this.workLog = workLog;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
class CombinedData{
private String org;
private List<String> worklogList;
private String rawData;
public String getOrg() {
return org;
}
public void setOrg(String org) {
this.org = org;
}
public List<String> getWorklogList() {
return worklogList;
}
public void setWorklogList(List<String> worklogList) {
this.worklogList = worklogList;
}
public String getRawData() {
return rawData;
}
public void setRawData(String rawData) {
this.rawData = rawData;
}
public void addToList(String worklog){
this.worklogList.add(worklog);
}
}
答案 0 :(得分:2)
我知道使用流减少行数很容易做到。
嗯,那不是真的。我只能建议您将方法添加到CombinedData
void add(Emp emp) {
if(getOrg()==null){
setOrg(emp.getCompany());
}
addToList(emp.getWorkLog());
if(getRawData()!=null){
setRawData(getRawData()+emp.getData());
}
else{
setRawData(emp.getData());
}
}
然后将其应用于流
CombinedData combinedData = new CombinedData();
empList.forEach(combinedData::add);
答案 1 :(得分:0)
顺便说一句,此特定步骤最好是对'combinedData'的操作:
if ( combinedData.getRawData() != null ) {
combinedData.setRawData( combinedData.getRawData() + emp.getData() );
} else{
combinedData.setRawData( emp.getData() );
}
combinedData.addRawData( emp.getData() );
这说明该代码对'combinedData'进行了多次调用。呼叫者真的需要知道'combinedData'的状态,还是要如何将现有的原始数据与新的原始数据结合在一起(通过串联在此处实现)?
(此外,如果您要添加同步/必须使此代码线程安全,则以这种方式进行操作会好得多。)