java - Java - 将数组字符串转换为数组列表

我有一个name和id的字符串,我需要将该字符串转换为对象列表。这是我的代码:


private List<ObjectAttribute> getDtls(String newVal) {


 ObjectAttribute object = new ObjectAttribute();


 List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();


 String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]


// String delimiter =",";


// newImageVal = newVal.split(delimiter);


 for (int i = 0; i <= newImageVal.length - 1; i++) {


 object.setImageName(newImageVal[i]);


 object.setImageId(newImageVal[++i]);


 objLst.add(object);


 }


 return objLst;


}



但是总是返回objList中的最后一个值。

时间:


private List<ObjectAttribute> getDtls(String newVal) {


 List<ObjectAttribute> objLst = new ArrayList<ObjectAttribute>();


 String[] newImageVal = [step0005.jpg, 172B6846-0073-4E5B-B10A-DDD928994EA6, step0003.jpg, FBC8D143-2CD7-47E6-B323-31A0928A9338]


// String delimiter =",";


// newImageVal = newVal.split(delimiter);


 for (int i = 0; i <= newImageVal.length - 1; i++) {


 ObjectAttribute object = new ObjectAttribute();


 object.setImageName(newImageVal[i]);


 object.setImageId(newImageVal[++i]);


 objLst.add(object);


 }


 return objLst;


}



移动


ObjectAttribute object = new ObjectAttribute();



在for循环中:


for (int i = 0; i <= newImageVal.length - 1; i++) {


 ObjectAttribute object = new ObjectAttribute();


 object.setImageName(newImageVal[i]);


 object.setImageId(newImageVal[++i]);


 objLst.add(object);


}



或者,你可以使用streams方法执行类似的操作:


AtomicInteger ai = new AtomicInteger(); 


List<ObjectAttribute> objLst = Arrays.stream(newImageVal)


.map(img-> {


 ObjectAttribute object = new ObjectAttribute();


 object.setImageName(img);


 object.setImageId(ai.getAndIncrement()); 


 return obj;


 }).collect(Collectors.toList())



...