java8获取list<Object>中最后一条数据
时间: 2024-02-21 13:56:52 浏览: 25
可以使用以下代码来获取List<Object>中的最后一条数据:
```
List<Object> list = new ArrayList<Object>();
// 添加数据到list中
Object lastObject = list.get(list.size()-1);
```
这段代码通过使用`list.size()-1`获取最后一个元素的下标,然后通过`list.get()`方法获取最后一个元素。
相关问题
java List<long>转List<String>,一条代码搞定
可以使用Java 8的Stream API来实现这个转换,代码如下:
List<Long> longList = Arrays.asList(1L, 2L, 3L);
List<String> stringList = longList.stream().map(Object::toString).collect(Collectors.toList());
这个代码将一个Long类型的List转换成了String类型的List,使用了Java 8的Stream API中的map()方法和collect()方法。
java 对List<ScheckTemplatesItemSpecific> itemList和子集List<ScheckTemplatesContentSpecific> contentList多条数据,按1 、1.1 1.2 1.3 、2 2.1 2.2 重新排序
可以使用如下代码对 itemList 和 contentList 进行重新排序:
```java
// 对 itemList 进行排序
Collections.sort(itemList, new Comparator<ScheckTemplatesItemSpecific>() {
@Override
public int compare(ScheckTemplatesItemSpecific o1, ScheckTemplatesItemSpecific o2) {
return o1.getItemNumber().compareTo(o2.getItemNumber());
}
});
// 对 contentList 进行排序
Collections.sort(contentList, new Comparator<ScheckTemplatesContentSpecific>() {
@Override
public int compare(ScheckTemplatesContentSpecific o1, ScheckTemplatesContentSpecific o2) {
return o1.getContentNumber().compareTo(o2.getContentNumber());
}
});
// 对 contentList 进行分组
Map<String, List<ScheckTemplatesContentSpecific>> contentMap = new HashMap<>();
for (ScheckTemplatesContentSpecific content : contentList) {
String[] arr = content.getContentNumber().split("\\.");
String key = arr[0];
List<ScheckTemplatesContentSpecific> list = contentMap.get(key);
if (list == null) {
list = new ArrayList<>();
contentMap.put(key, list);
}
list.add(content);
}
// 合并 itemList 和 contentList
List<Object> resultList = new ArrayList<>();
int i = 0;
for (ScheckTemplatesItemSpecific item : itemList) {
resultList.add(item);
String key = item.getItemNumber();
List<ScheckTemplatesContentSpecific> list = contentMap.get(key);
if (list != null) {
Collections.sort(list, new Comparator<ScheckTemplatesContentSpecific>() {
@Override
public int compare(ScheckTemplatesContentSpecific o1, ScheckTemplatesContentSpecific o2) {
return o1.getContentNumber().compareTo(o2.getContentNumber());
}
});
resultList.addAll(list);
}
}
```
这段代码首先对 itemList 和 contentList 分别按照编号进行排序,然后对 contentList 进行分组,将同一个父级编号的子集放在一起。最后,将 itemList 和对应的子集合并到一起,得到重新排序后的结果。