简体   繁体   中英

How to compare two numbers in Arraylist?

I want to compare two numbers in arraylist,but I failed,anyone can help me,here is my code.

MainActivity{
ArrayList<User> users=new ArrayList<User>();
            users.clear();
            int imgid;
            int number=0;
            User use1;
            List<User> user=DataSupport.findAll(User.class);
            for (User use:user){
                use1=new User();
                use1.setNeednumber(use.getNeednumber());
                use1.setMaterialid(use.getMaterialid());
                users.add(use1);
            }
for(int i=1;i<users.size();i++){
                if(users.get(i-1).getMaterialid()==users.get(i).getMaterialid()){

number=number+users.get(i-1).getNeednumber();
                    Log.d("number",""+number);
                }
            }

On the whole,it's like this,I use Litepal to create an database,the database have a table called "User",the table have two column one is "Materialid" one is "Neednumber",I want read the data what I storage in this table and if the "Materialid" is equal let them add.I use above method but it didn't work,the number always zero.who can help me deal with this problem ,thank you very much.

try this logic

    Integer numberArray[] = { 1, 2, 45, 6, 7, 7, 8, 9, 10, 11, 10, 9, 1 };
    Set<Integer> printed = new HashSet<>();
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (Integer s : Arrays.asList(numberArray)) {
        if (printed.add(s)) // Set.add() also tells if the element was in
                            // the Set!
            System.out
                    .println("element: " + s + ", count: " + Collections.frequency(Arrays.asList(numberArray), s));

        if (Collections.frequency(Arrays.asList(numberArray), s) > 1) {
            map.put(s, Collections.frequency(Arrays.asList(numberArray), s));
        }
    }
    Integer sum = 0;
    for (Map.Entry m : map.entrySet()) {
        System.out.println(m.getKey() + " " + m.getValue());
        sum = sum + ((Integer) m.getKey() * (Integer) m.getValue());
    }
    System.out.println("sum is" + sum);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM