How to sort Java ArrayList [duplicate] - java

This question already has answers here:
Sort ArrayList of custom Objects by property
(29 answers)
Closed 9 years ago.
Ive got a file called HighScores.txt which contains player names and number of points:
name1 2
name2 5
name3 1
name4 23
name5 51
And heres my code that reads the contents of this file, splitting each line and appending it to the ArrayList highScores:
public class fileHandling {
static ArrayList highScores = new ArrayList();
public static void readFile(String[] args) throws Exception {
File file = new File(fileHandling.class.getClassLoader()
.getResource("HighScores.txt").getPath());
Scanner read = new Scanner(file);
while (read.hasNextLine()) {
String line = read.nextLine();
String[] result = line.split("\\s+");
highScores.add(Arrays.toString(result));
System.out.println(highScores);
}
}
}
How do i then sort this ArrayList by the number of points each player has?
i.e. so the new array list will be:
[[name5, 51], [name4, 23], [name2, 5], [name1, 2], [name3, 1]]

You can create a separate object for every line in your file and then use Comparable or Comparator interface to sort these objects. Then use Collections.sort(arrayList,sorter).
You can find a good tutorial here to sort user defined objects.
The class for the same can be
public class Player{
private String name;
private Integer score;
//getters and setters here
}
Then create a sorter for Player objects as follows.
public class ScoreSort implements Comparator<Player>{
public int compareTo(Player first, Player second){
// implement sorting logic here
}
}
Then use Collections.sort(playerList, new ScoreSort()). You can find a good tutorial at following link
http://www.thejavageek.com/2013/06/17/sorting-user-defined-objects-part-2/

Create a class with 2 member variable name and score. Create a new instance of class for each entry in file and store it in ArrayList.
Now this class should also implement Comparable interface which compares based on score. Now use Collections.sort

Related

Java abstract Issue [duplicate]

This question already has answers here:
"Instantiating" a List in Java? [duplicate]
(6 answers)
How to declare an ArrayList with values? [duplicate]
(6 answers)
Closed 4 days ago.
Hi i want to fix this error
java: java.util.List is abstract; cannot be instantiated.
I tryied to add extends to second file but this dont work
idk cause this error
i m new in java programming and i need help
I added code below
Thx for help
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner =new Scanner(System.in);
System.out.println("What you want to do");
System.out.println("1.EDIT BOOKS");
System.out.println("2.BORROWING AND RETURNING BOOKS");
System.out.println("3.SEARCH FOR BOOK");
var x =scanner.nextInt();
switch (x) {
case 1:
System.out.println("1.ADD BOOK");
System.out.println("2.DELETE BOOK");
var z =scanner.nextInt();
switch (z){
case 1:
System.out.println("Enter book name");
String name=scanner.nextLine();
System.out.println("Enter username");
String user=scanner.nextLine();
List list= new List(user,name);
}
;break;
case 2: System.out.println("2");break;
case 3: System.out.println("2");break;
}
}
}
import java.util.HashMap;
public class LIST {
String bookname;
String user;
void newuser(String user,String bookname){
this.user=user;
this.bookname=bookname;
}
HashMap<String,String> Books =new HashMap<String,String>();
}
List.of
To instantiate an unmodifiable List using literals syntax, use List.of methods.
List< String > list = List.of( user , name ) ;
As commented by Dave Newton, you cannot actually instantiate an interface such as List. Under the covers, the .of method has a default implementation. That implementation instantiates an object of some unspecified concrete class that implements the List interface.
Adding to a list
I am guessing the purpose of your app is to collect info about multiple people and their favorite or borrowed book. If so you should collect those pieces of data as fields on an object of a custom class.
A record is a brief way to declare a custom class whose main purpose is to communicate data transparently and immutably.
record BookUser ( String user , String book ) {}
Make a list to collect multiple objects. An ArrayList is a modifiable List.
List< BookUser > bookUsers = new ArrayList<>() ;
Instantiate objects, and collect.
BookUser bu = new BookUser( user , name ) ;
bookUsers.add( bu ) ;

Using foreach loop with methods in another class (Java) [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 6 years ago.
I have a program that creates a couple objects and adds each one to an ArrayList, then is supposed to loop over each object in the ArrayList and use a getter from another class within the project to display information on each object. I can't get the objects in my foreach loop to use any of the methods in my other class. Here is my main, including the trouble loop at the bottom:
import java.util.ArrayList;
public class ITECCourseManager {
public static void main(String[] args) {
ArrayList ITECCourse = new ArrayList();
ITECCourse infotech = new ITECCourse("Info Tech Concepts", 1100, 5, "T3050");
infotech.addStudent("Max");
infotech.addStudent("Nancy");
infotech.addStudent("Orson");
ITECCourse.add(infotech);
ITECCourse java = new ITECCourse("Java Programming", 2545, 3, "T3010");
java.addStudent("Alyssa");
java.addStudent("Hillary");
ITECCourse.add(java);
for (Object course : ITECCourse) {
System.out.println("Name: " + course.getName());
}
}
}
And here is the other class in my project with the method I need to use:
public class ITECCourse {
public String name;
public int code;
public ArrayList<String> students;
public int maxStudents;
public String room;
ITECCourse(String courseName, int courseCode, int courseMaxStudents, String roomNum) {
name = courseName;
code = courseCode;
maxStudents = courseMaxStudents;
students = new ArrayList<String>();
room = roomNum;
}
public String getName() {
return name;
}
If I replace course.getName() with java.getName(), the code works. I'm confused why I can't use a foreach loop across the ArrayList to use the getter for each object, when I am able to call the object and use the method directly from the same place in the code.
Edit: Thank you for the answers, simple mistake only had to make two/three changes: declare ArrayList<ITECCourse> at the beginning, change Object in for loop to ITECCourse, and of course change my arraylist from ITECCourse to ITECCourseList so there isn't confusion with my ITECCourse class.
The call to course.getName() doesn't work because you've defined course as an Object in your loop and Object doesn't have the method getName(). If you add a type parameter to your ArrayList declaration such as ArrayList<ITECCourse>, then you can iterate over the list of ITECCourse instances rather than Object.
On a side note, naming your variable ITECCourse will just lead to confusion because it's the same as your class. Might be better to name your variable something like itecCourseList.

Appending List to List [duplicate]

This question already has answers here:
Add ArrayList to another ArrayList in java
(6 answers)
Closed 7 years ago.
I'm writing a class called List which creates an instance variable array of Customers (Customer is just another class that accepts String parameters for a person's name),
i.e private Customer[] data
I'm trying to write an append method that will take a Customer and add it to another List in the main method.
To do this, there seems to be a method called addAll(), but since I'm writing this code by scratch, I can't use this. I looked at the pseudo code though for this method to get a general idea and it converts the Object into an array and then uses arraycopy to append the two lists.
I meant to say, this way makes sense to me, if I were using arrays, but I'm trying to add a Customer object from another list and add them to a list in the main method.
Not sure of what you want, but I think you can implement the append method yourself just as what the arraycopy method do. Here is a simple example
class List {
private int size;
private Customer[] data;
private final static int DEFAULT_CAPACITY = 10;
public List() {
size = 0;
data = new Customer[DEFAULT_CAPACITY];
}
public void append(List another) {
int anotherSize = another.size;
for (int i = anotherSize - 1; i >= 0; --i) {
if (size < data.length) {
data[size++] = another.data[i];
another.data[i] = null;
another.size--;
} else {
throw new IndexOutOfBoundsException();
}
}
}
}

How to sort object array? [duplicate]

This question already has answers here:
How to sort an array of objects in Java?
(11 answers)
Sort ArrayList of custom Objects by property
(29 answers)
Closed 8 years ago.
I have an object array like
Player p[] = new Player[t];
And every object has an integer variable and a name variable.
public class Player {
public String player_name;
public int number;
}
After getting input from user how can I sort this object array according to their number variable?
With Java SE 8 try something like (untested):
Arrays.stream(p).sorted((p1, p2) -> Integer.compare(p1.number, p2.number)) .collect(Collectors.toList())
Edit
On second thought this might be more efficient in this case, as it doesn't create a new array/ collection:
Arrays.sort(p, (p1, p2) -> Integer.compare(p1.number, p2.number));
The easiest way is to make Player implement Comparable<Player>, and implement the compareTo(Player) method inside Player:
public int compareTo(Player player) {
return this.number-player.number;
}
Then, wherever you want to sort the array, just call Arrays.sort(p);
Create a class that implements Comparator<Player>, called say PlayerComparator. Implement the interface by creating a compare method that takes two Players. Return a negative number, zero, or a positive number, depending on whether the first Player is considered less than, equal to, or greater than, the second Player.
Then you can create your PlayerComparator and pass it (along with your array) to Arrays.sort.
let your custom class implements Comparable interface and then you can use java Collection to sort your array (Arrays.sort() function)
public class Player implements Comparable<Player> {
public String player_name;
public int number;
#Override
public int compareTo(Player object) {
return this.player_name.compareTo(object.player_name);
}
}
sort
Player p[] = new Player[t];
// do stuff
Arrays.sort(p);
You'd need to have a getter on the number variable for this to work, like:
public class Player {
public String player_name;
public int number;
public int getNumber() {
return number;
}
}
Then, as of Java 8, you can sort it by using the Comparing factory class:
Player[] p = new Player[t];
Arrays.sort(p, Comparator.comparingInt(Player::getNumber));
This will:
Create a Comparator<Person>, by comparing no the getNumber method.
What you see here is a method reference, which is shorthand for the lambda p -> player.getNumber(), which maps the player to the number.

Sort an ArrayList of object by title property [duplicate]

This question already has answers here:
Sorting a list of points with Java [duplicate]
(4 answers)
How do I use Comparator to define a custom sort order?
(9 answers)
Closed 9 years ago.
I have an objects class that holds the properties title, director, genre, rating. I have created an arraylist and have filled it with instances of this base class
ArrayList<Movie> movieCatalog
I am wanting to sort this ArrayList in alphabetical order by the title property and change their positions within the ArrayList. From my research I understand I need to use a Comparator class but I am confused about how to do this.
You can create a custom comparator and than call the Collections.sort(movieCatalog,comparator); method.
E.g.
public static final Comparator<movieCatalog> movieComparator = new Comparator<movieCatalog>() {
public int compare(movieCatalog a1, movieCatalog a2) {
return a1.name.compareTo(a2.name);
}
};
Collections.sort(movieCatakig,movieComparator);
Your Movie class needs to implement Comparable<Movie>. Then you need to implement the compareTo method, which in this case can just call the String class compareTo method.
int compareTo(Movie other) {
return this.title.compareTo(other.title);
}
After that, if movies is an ArrayList of movies, you can simply do
Collections.sort(movies);

Categories