我有很多主列表,并且其中有一个子列表。
如何通过Java 8访问子列表并进行编辑。
示例。
List<Student> list = ....;
list[0] = {id = 1, name = "aa", ListMinute = List<String> ls1}
list[1] = {id = 2, name = "bb", ListMinute = List<String> ls2}
list[2] = {id = 3, name = "cc", ListMinute = List<String> ls3}
list[3] = {id = 4, name = "dd", ListMinute = List<String> ls4}
列表[0]的子列表示例:
List<String> ls1 = {"120", "150", "45", "195"}; //List in minutes.
如何将所有子列表从分钟转换为小时和分钟。
list [0]的子列表的输出:
List<String> ls1 = {"2", "2.30", "0.45", "3.15"}; // List in hours and minutes.
答案 0 :(得分:3)
获得转化的方法之一可能是:
List<String> ls1 = List.of("120", "150", "45", "195"); //List in minutes.
List<String> out = ls1.stream()
.mapToInt(Integer::parseInt)
.mapToObj(min -> String.format("%d.%d", min / 60, min % 60))
.collect(Collectors.toList());
// would output 2.0 instead of 2 though
如果要更新现有的List
,可以尝试replaceAll
List<String> ls1 = Stream.of("120", "150", "45", "195").collect(Collectors.toList()); //List in minutes.
ls1.replaceAll(a -> {
int min = Integer.parseInt(a);
return String.format("%d.%d", min / 60, min % 60);
});
答案 1 :(得分:1)
正如@nullpointer所说,您可以使用list
来修改replaceAll
实例,例如
list.stream()
.map(Student::getListMinute)
.forEach(minutes ->
minutes.replaceAll(min -> format("%d.%d", parseInt(min) / 60, parseInt(min) % 60))
);