Collections trong Java

Hiện tại em muốn tìm giá sản phẩm lớn nhất trong một List object của em và sau đó in ra nó. E dùng Collections.max nhưng lại không biết triển khai thế nào cho đúng, e đã tìm mất 1 tgian nhưng chỉ toàn thấy collection.sort . Mong anh chị gợi ý, E cảm ơn :smile:
Đây là code của em.

ArrayList<oto> list = new ArrayList<oto>();
	public oto b;
	public Float gia;
	public String nhanhieu;
	int n;
	public void nhap()
	{
		Scanner z = new Scanner(System.in);
		do
		{
			System.out.println("Nhao vao so oto");
			n =Integer.parseInt(z.nextLine());
			if(n<2)
			{
				System.out.println("Nhap lai");
			}
		}while(n<2);
		for(int i=0; i<n; i++)
		{	
			b = new oto();
			System.out.println("nhap vao nhan hieu");
			b.nhanhieu = z.nextLine();
			System.out.println("Nhap vao gia");
			b.gia = Float.parseFloat(z.nextLine());
			list.add(b);
		}
	} 
	public void max()
	{
		Collections.max(list, new Comparator<oto>() {

			@Override
			public int compare(oto o1, oto o2) {
				// TODO Auto-generated method stub
				return 0;
			}

	
	});

em phải implement hàm này chứ. lấy giá ra so sánh

2 Likes

a chỉ cho em rõ hơn với. Nếu so sanh o1.gia > o2.gia rồi return về 1,-1,0 thì nó lại là kiểu sắp xếp rồi ạ.

trông giống kiểu sắp xếp không có nghĩa là nó sẽ là sắp xếp, bản chất cái comparator vẫn chỉ là hướng dẫn library cách so sánh 2 instance. Tìm max, tìm min, sắp xếp thì vẫn phải so sánh 2 object bất kì thì việc bạn trông nó giống là điều đương nhiên

2 Likes

public void max()
{
Collections.max(list, new Comparator() {

		@Override
		public int compare(oto o1, oto o2) {
			// TODO Auto-generated method stub
			if(o1.gia>o2.gia)
				return 1;
			else if(o1.gia<o2.gia)
				return -1;
			else
			return 0;
		}
});
	for (oto oto : list) {
		System.out.println(oto.gia);
	}

}
sau khi e sửa xong r nhập giá thì nó sắp xếp theo thứ tự tăng dần. @@

Code thủ công vậy. Không biết có cách nào hay hơn không?

class Oto{
    private int price;

    public Oto(int price) {
        this.price = price;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }
}

class Demo{
    public static void main(String argv[]) {
        List<Oto> list = new ArrayList<>();
        list.add(new Oto(5));
        list.add(new Oto(2));
        list.add(new Oto(30));
        list.add(new Oto(20));
        System.out.println("Max: " + getMaxPrice(list));

    }

    public static int getMaxPrice(List<Oto> list) {
        Oto oMax = new Oto(0);
        for (Oto o : list) {
            if (o.getPrice() > oMax.getPrice()) {
                oMax = o;
            }
        }
        return oMax.getPrice();
    }

}

Nếu thích bạn có thể sử dụng Java 8, sẽ ngắn gọn hơn:

list.stream()
.max(Comparator.comparing(Oto::getPrice))
.get();

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?