enter image description here How i can sort array of node class according to marks value
CodePudding user response:
You have few ways to do that. Here are the 2 that came to my mind:
- When defining your Node class, implements the Comparator interface as follows:
@Getter
@Setter
@ToString
@AllArgsConstructor
public class Node implements Comparable<Node> {
private int marks;
private int index;
@Override
public int compareTo(Node o) {
return Integer.compare(this.marks, o.marks);
}
}
Then when you use the Arrays.sort(yourNodeArray), then the array yourNodeArray is sorted by the marks.
- Another method is to use streams:
Node[] yourSortedNodeArray = Arrays.stream(yourNodeArray).sorted(Comparator.comparing(Node::getMarks)).toArray(Node[]::new);
With the first way, you will always sort by the marks, the second way, you can sort by anything you want.
CodePudding user response:
Please understand how to ask questions properly according to the StackOverFlow Rules and always let other know what you did and what challenges are you facing? This time I am not down voting your question but from next time please keep that in mind. Go through this to unserstanc about how to ask proper questions https://www.wikihow.com/Ask-a-Question-on-Stack-Overflow
Share the question link and your solution as well.So that I can have a look.
