Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that List<Long> contains a value?

I have list List<Long> list, that contains: [160774, 7212775] and Long id = 7212775. I need to check if the list contains an element with value of id. How to do that? Unfortunately list.contains(id) returns false in my case.

I'm using it that way:

@RequestMapping("/case/{id}")
public String openCase(@PathVariable("id") Long id) {

    log.debug(caseDAO.findAllCasesId());    // [160774, 7212775]
    log.debug(id); // 7212775

    if(caseDAO.findAllCasesId().contains(id)) {
        return "case";
    } else {
        return "404";
    }
}

Piece of DAO (Hibernate, but native sql here):

public List<Long> findAllCasesId() {
    String sql = "select id from cases";
    SQLQuery query = getSession().createSQLQuery(sql);
    return query.list();
}

SOLVED

The problem was with caseDAO.findAllCasesId(), that return list of Object, not list of Long. I corrected this by:

SQLQuery query = getSession().createSQLQuery(sql).addScalar("id", Hibernate.LONG);

Big thanks to: Nayuki Minase

like image 692
marioosh Avatar asked Aug 18 '11 20:08

marioosh


People also ask

How do you check if an ArrayList contains a value?

ArrayList. contains() method can be used to check if a Java ArrayList contains a given item or not. This method has a single parameter i.e. the item whose presence in the ArrayList is tested. Also it returns true if the item is present in the ArrayList and false if the item is not present.

How do you check if a list only contains a certain item Java?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

Which method is used by the Contains () method of a list to search an element Mcq?

contains() method in Java is used to check whether or not a list contains a specific element. To check if an element is in an array, we first need to convert the array into an ArrayList using the asList() method and then apply the same contains() method to it​.


2 Answers

When autoboxing, you need to make sure you postfix the literal with an L i.e. Long id = 7212775L for this to work.

like image 143
Sanjay T. Sharma Avatar answered Sep 19 '22 09:09

Sanjay T. Sharma


Running the code below on eclipse helios:

public static void main(String[] args) {
    List<Long> list = new ArrayList<Long>();
    list.add(160774L);
    list.add(7212775L);
    System.out.println(list.contains(7212775L);
}

Output:

true

What you're doing wrong is

System.out.println(list.contains(7212775));

The problem is that your list takes Long objects and you are searching for a literal.

like image 25
Dhruv Gairola Avatar answered Sep 20 '22 09:09

Dhruv Gairola