[英]JAVA: How to convert String ArrayList to Integer Arraylist?
[英]How to convert a ArrayList of Objects into List of Integer in java
我使用此本地查询来获取数据。 select c.id,c.name from customer c,information i where i.status=1 and c.id=i.customerId
并且我使用以下代码将对象列表转换为整数列表,如下所示:
public List<Integer> getAllIdsByGroupId(Integer groupId) throws Exception {
List<Object[]> list = repository.getAllIdsByGroupId(groupId);
List<Integer> ids = repository.mapIds(list);
return ids;
}
public List<Object[]> getAllIdsByGroupId(Integer groupId) {
Query query = entityManager.createNativeQuery("select c.id,c.name from customer c,information i where i.status=1 and c.id=i.customerId and c.groupId=:groupId");
query.setParameter("groupId", groupId);
List<Object[]> list = query.getResultList();
if (list == null || list.isEmpty()) {
return null;
}
return list;
}
public List<Integer> mapIds(List<Object[]> list) {
List<Integer> ids = new ArrayList<Integer>();
if (list != null && !list.isEmpty()) {
Integer id;
for (Object[] object : list) {
id = (object[0] != null ? (Integer) object[0] : null);
ids.add(id);
}
}
return ids;
}
该查询检索具有ID和名称的列表。上面的代码无例外地给出了输出。但是我要求仅具有ID的列表。 当我按如下方式从查询中删除c.name时, select c.id from customer c,information i where i.status=1 and c.id=i.customerId
上面的代码失败并产生异常
java.lang.Integer cannot be cast to [Ljava.lang.Object;
有帮助吗? 提前致谢。
如果您使用JPA / Hibernate来获取单列数据,则它隐式返回List<Integer>
(基于该列的类型),因此无需将其转换为Integer列表。
一般规则:
问题出在类型转换Change List<Object[]> list = query.getResultList();
到List<Object> list = query.getResultList()
它是您的代码尝试转换的对象列表,并将整数转换为数组列表。
如果您只是尝试获取ID,则List<Integer> list = query.getResultList()
也将足够
试试这个可能不会在我的编辑器中尝试,但是我想这个解决方案之一可以帮助您。
public List<Integer> mapIds(List<Object[]> list) {
List<Integer> ids = new ArrayList<Integer>();
if(list != null && !list.isEmpty()) {
int id;
for(Object[] object : list) {
id = (int) (object[0] != null ? object[0] : null);
ids.add(id);
}
}
return ids;
}
虽然问题是缺乏大量的信息,对最可能的原因ClassCastException
是你想投未中键入对象Integer
输入Integer
。 我不确定要传递给方法的列表中有什么,但是如果列表确实包含一些Integer
类型的对象,那么您可以尝试在将element object[0]
转换为Integer
之前检查一下,
public List<Integer> mapIds(List<Object[]> list) {
List<Integer> ids = new ArrayList<Integer>();
if (list != null && !list.isEmpty()) {
Integer id;
for (Object[] object : list) {
id = ((object[0] != null && object[0] instanceof Integer) ? (Integer) object[0] : null);
ids.add(id);
}
}
}
return ids;
}
但是,如果list
的对象不包含任何Integer
对象,则实现您正在执行的操作的唯一方法是通过某种方式检索每个int
值来为每个object[0]
初始化一个Integer
对象。 只有您知道如何执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.