如何找到对象的数组的第二大元件 [英] How to find the second largest element in an array of objects

查看:73
本文介绍了如何找到对象的数组的第二大元件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道找对象的数组中的第二大元素的方法。对于如。
如果有像书籍名称,价格属性的Book类对象的数组,在库存数量

I need to know the way to find the second largest element among an array of objects. for eg. if there is an array of objects of a Book class with attributes like book name, price, in stock quantity

Book[] b=new Book[];
b[0]=new Book("x",200,50);
b[1]=new Book("y",100,44);
b[2]=new Book("z",500,29);

我们如何可以列出书第二大的价格与类似名称,并在库存量

How can we list the book with second largest price along with other attributes like name and in stock quantity

推荐答案

请在列表 图书从中,使用它进行排序 Col​​lections.sort ,并采取元素索引1。

Make a List of Books from it, sort it using Collections.sort and take the element on index 1.

    List<Book> booklist = new ArrayList<Book>(Arrays.asList(b));

    Collections.sort(booklist, new Comparator<Book>() {

        @Override
        public int compare(Book o1, Book o2) {

            return o2.getPrice() - o1.getPrice();
        }
    });
    if (booklist.size() > 1) {
        System.out.println(booklist.get(1));
    }

这篇关于如何找到对象的数组的第二大元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆