如何按字符串对象的升序对对象数组进行排序?

时间:2020-02-08 15:20:07

标签: java arrays string class sorting

我必须接受用户输入(整数ID,字符串标题,字符串文件夹,整数页)。我必须按字符串标题(字典顺序)的升序获取输出。我已经编写了代码,但是输出却大不相同。

package zzz;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;

class Book{
    int id;
    String title;
    String folder;
    int pages;
}


public class practice {

    public static void main(String[] args)throws Exception {
        // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    Book b1 = new Book();
    Book b2 = new Book();
    Book b3 = new Book();
    Book b[]= {b1,b2,b3};
    for(int i=0;i<b.length;i++) {
        b[i].id=sc.nextInt();
        sc.nextLine();
    b[i].title=sc.next();
        sc.nextLine();
        b[i].folder=sc.next();
        b[i].pages=sc.nextInt();
    }
    Book temp = null;
    for(int i=0;i<b.length;i++) {
        for(int j=0;j<b.length-1-i;j++) {
            if(b[i].title.compareTo(b[j].title)<0) {
             temp =b[j];
            b[j]=b[j+1];
            b[j+1]=temp;
        }}
    }
    for(int i=0;i<b.length;i++) {
        System.out.println(b[i].id+" "+b[i].title+" "+b[i].folder+" "+b[i].pages);
    }

    }}

enter image description here

4 个答案:

答案 0 :(得分:2)

我将在开头删除该类,并在main方法之后添加该类,如下:

static class Book implements Comparable<Book>{
    int id;
    String title;
    String folder;
    int pages;

    @Override
    public int compareTo(Book other) {
        //If this is backword then switch it to -> other.title.compareTo(this.title);
        return this.title.compareTo(other.title);
     }
}

与:Implements Comparable to get alphabetical sort with Strings

然后,您可以获取书本并使用Arrays.sort(book_arr);

为您:

package zzz;
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;


public class practice {

    public static void main(String[] args)throws Exception {
        // TODO Auto-generated method stub
    Scanner sc = new Scanner(System.in);
    Book b1 = new Book();
    Book b2 = new Book();
    Book b3 = new Book();
    Book b[]= {b1,b2,b3};
    for(int i=0;i<b.length;i++) {
        b[i].id=sc.nextInt();
        sc.nextLine();
        b[i].title=sc.next();
        sc.nextLine();
        b[i].folder=sc.next();
        b[i].pages=sc.nextInt();
    }

    //Sort!
    Arrays.sort(b);

    for(int i=0;i<b.length;i++) {
        System.out.println(b[i].id+" "+b[i].title+" "+b[i].folder+" "+b[i].pages);
    }

    }
    static class Book implements Comparable<Book>{
        int id;
        String title;
        String folder;
        int pages;

        @Override
         public int compareTo(Book other) {
             return this.title.compareTo(other.title);
         }
     }
}

It works!

答案 1 :(得分:0)

因为b[i].title=sc.next();已被注释掉,所以您得到NullPointerException。

不使Book Comparable可实现此目的的一种方法是对流进行排序:

Stream.of(b)
    .sorted((thisBook,anotherBook) -> thisBook.title.compareTo(anotherBook.title))
    .forEach(bk -> System.out.println(bk.id+" "+bk.title+" "+bk.folder+" "+bk.pages));
}

答案 2 :(得分:0)

我相信您必须已经通过Implements Comparable to get alphabetical sort with Strings

以下是完整的代码:

    android:background="@android:color/transparent"

示例运行:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_red_dark"
    android:paddingTop="?attr/actionBarSize">

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/nav_view"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="@android:color/transparent"
        app:itemIconTint="@android:color/black"
        app:itemTextColor="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/bottom_nav_menu" />

</androidx.constraintlayout.widget.ConstraintLayout>

答案 3 :(得分:0)

您可以在Java 8中使用stream来简单地处理问题,因此可以使用array来代替List,然后必须 stream 初始化,最后根据其title对书籍进行排序

夏日

1-创建Book对象(与您的对象相同)

2-创建图书清单(而不是数组)

3- bookList,初始化每个书对象,然后根据标题排序

4-打印结果

我对您的情况进行了如下编码

public static void main(String[] args)  {

        //Create Book Objects
        Scanner sc = new Scanner(System.in);
        Book b1 = new Book();
        Book b2 = new Book();
        Book b3 = new Book();

        //Create BookList
        List<Book> bookList = new ArrayList<>();
        bookList.add(b1);
        bookList.add(b2);
        bookList.add(b3);

        //Stream bookList, Init Books, Sort them based on the title
        bookList.stream().peek(book -> {

            //Init book objects (id , folder , title , pages)
            book.id = sc.nextInt();
            sc.nextLine();
            book.folder = sc.next();
            sc.nextLine();
            book.title = sc.next();
            sc.nextLine();
            book.pages = sc.nextInt();          

        }).sorted(Comparator.comparing(book -> book.title)).collect(Collectors.toList());


        //Print results
        bookList.forEach(book -> {
            System.out.println(book.title);
        });
    }