simplifying java array layout - java

is there any other way of applying this table to array rather than creating 31 of them?
The layout looks like:
state_name|year|crimetype1|crimetype2|place|count|
row1: state1|2001|murder|knife|home|5|
row2: state1|2001|murder|axe|home|2|
row3: state2|2001|robbery|baseball|shop|1|
and so on for 31 different states.
I thought of creating 31 arrays for each state with 5 rows but is there any other way of making it simpler?

Simply put: objects. That way, you will not have to have nested arrays.
Make a class:
public class Crime{
private int year;
private String state;
private String crimeType1, crimeType2;
private String place;
private int count;
//And then you'd have some useful stuff here...
}
Besides this, I don't think you should combine the 31 values anymore - they are 31 separate, independent occurrences.

First, create a Crime object which can represent a single row in that collection. Let's make it naturally comparable against itself based on the state.
public class Crime implements Comparable<Crime> {
private String state;
private Year year;
private String crimeType1;
private String crimeType2;
private String place;
private int count;
public int compareTo(Crime other) {
return state.compareTo(other.state);
}
}
I leave the construction of this object as an exercise for the reader.
Next, you'll want to add the results of that value to a list.
List<Crime> crimes = new ArrayList<>();
// In a loop reading the file
crimes.add(crime);
At this point your work is pretty much done; if you want to get the crimes by a specific state, you can use the Stream API to filter based on that.

It is better to create class Crime as follows
getHeader() returns header and getRow will return the row . (or toString)
public class Crime {
String stateName;
String year;
//...
public static String getHeader(){
//you can improve this
return "state_name|year|crimetype1|crimetype2|place|count|";
}
public String getRow(){
return stateName + "|" + year +"|" ...
}
public static void main(String[] args) {
List<Crime> state = new ArrayList<>(31);
//or
List<Crime> state = Arrays.asList(new Crime[] {
new Crime("ST","2004",..),...
});
}
}

as KevinO pointed if you are coding OO language it is good to think in OO way otherwise there no point of using java.
Create a Crime class with all the values except state and then a Map
Map<String,ArrayList<Crime>> multiMap = new HashMap<String,ArrayList<Crime>>();
Here String is state name and the ArrayList for all the crimes in that state, So at the end there will be 31 keys (Here we are using state as unique keys) in muliMap Object.
So later you no need to filter statewise crimes, all you need to do is
ArrayList<Crime> state1Crimes = multiMap.get("state1");
Simple and straight forward.

Related

HashMap with multiple values get.key() error

import java.util.*;
class Student{
final String name;
final String gender;
public String number;
static Map<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
static ArrayList<String> nameandNumber = new ArrayList<>();
Student(String number, String name, String gender) {
this.name = name;
this.gender = gender;
this.number = number;
nameandNumber.add(this.name);
nameandNumber.add(this.number);
hm.put(this.gender,nameandNumber);
}
void getPersonByGender() {
String[] Liste = hm.get("Man").toArray(new String[0]);
for (int i = 0; i < Liste.length - 1; i += 2) {
System.out.println(Liste[i] + "\t<------>\t" + Liste[i + 1]);
}
}
}
hello guys i am creating a class and this class will return me 10 student information which I will give (according to the difference between men and women). When i try to use getPersonByGender's function this function gives me all students.
static ArrayList<String> nameandNumber = new ArrayList<>();
new is useful: Count the amount of times your code ever invokes new ArrayList. It's a fairly easy answer: Once. For your entire program.
If you only call new once, that means there is only one list. In the whole system.
No wonder then: This:
nameandNumber.add(this.number);
is called 10 times (because 10 students) for a single 'run' of your app. Thus, that one list you have must therefore have all these numbers added together - that's why you see all the data.
Your code is, unfortunately, layers of bad design decisions.
You can 'fix' the problem (but it'll still be fragile code that is hard to read), or you can 'fix' the design (which is more work).
Fix the problem
Instead of 1 list shared by all students which obviously can't work, you want to call new ArrayList for each student. Get rid of that static single arraylist, and instead make one every time:
Student(String number, String name, String gender) {
this.name = name;
this.gender = gender;
this.number = number;
var nameandNumber = new ArrayList<String>();
nameandNumber.add(this.name);
nameandNumber.add(this.number);
hm.put(this.gender, nameandNumber);
}
Now you call new ArrayList the right number of times throughout one run of your program, for example.
But you're still in trouble here - because you decided to use a List to represent a single idea (a student), you have confused yourself: A given gender maps to multiple students. Given that a single student is represented by a List<String>, multiple students would be a List<List<String>> and, oof, this is getting real complex, real fast.
We could plug away at fixing this further but let's take a step back and fix your design instead!
Fix the design
More generally, java's typing system is highly nominal: Types have names, and the more descriptive the name, the better.
Student is a far better, clearer name than List<String>. How is a reader of your code supposed to know that those List<String> objects specifically are intended to contain precisely 2 strings, the first of which is the student's name, the second of which is their student ID number? It doesn't say that anywhere. If you mess it up you get no compiler errors of any kind.
You have a type, right there, that properly describes that concept: Student!
So why not replace this bad code:
static Map<String, ArrayList<List<String>>> hm = new HashMap<String, ArrayList<List<String>>>();
With this much improved code:
static Map<String, List<Student>> genderMap = new HashMap<>();
It has all sorts of improvements:
It has a proper name. hm doesn't mean anything.
It uses <> to be shorter - you don't need to repeat that stuff.
It codes to the principle (List) instead of the concrete class.
It uses nominal types - this maps a gender string to a list of students. And the code reads the same way, that's good.
Putting it together:
class Student {
final String name;
final String gender;
final String number;
static Map<String, List<Student>> genderMap = new HashMap<>();
Student(String number, String name, String gender) {
this.name = name;
this.gender = gender;
this.number = number;
List<Student> studentsForThisGender = genderMap.get(gender);
if (studentsForThisGender == null) {
// There is no list yet; we need to make one.
genderMap.put(gender, studentsForThisGender = new ArrayList<>());
}
studentsForThisGender.add(this);
}
static void getPersonByGender() {
Student[] liste = genderMap.get("Man").toArray(new Student[0]);
for (Student student : liste) {
System.out.println(student.name + "\t<------>\t" + student.number);
}
}
}
Note:
getPersonByGender is now static - that's a thing you do to the concept of 'students' not any particula student.
Instead of this nebulous 'print list[0] - you just sorta have to know that's the name', we print student.name which documents itself.
We fixed the problem where you were list-confused.
If you get a little further along your java studies, that 'get the list of students for a given gender, and make a new list if neccessary' can be put more succintly. The last 4 lines can be reduced to:
genderMap.computeIfAbsent(gender, () -> new ArrayList<>()).add(this);
But I bet that syntax, and what is happening there, hasn't been covered yet in your java course.

Comparing values within an object array for one specific field for Mergesort. Beginner question about using compareTo

Pretty simply, we have to implement a sorting function of our own choice to sort through a database of customers. The customers are imported from an excel file and stored in an array. I have chosen Mergesort to make a different question involving big O notation a slam dunk.
Here's the import and the creation of the array
Scanner sc = new Scanner(new File("customers.csv")); Customer[] customers = new Customer[1000];
The customer class looks like this
`
class Customer implements Comparable{
private int cusNo;
private String dateOfBirth;
private String firstName;
private String lastName;
//The constructor
public Customer(int cusNo, String dateOfBirth, String firstName, String lastName)
{
this.cusNo = cusNo;
this.dateOfBirth = dateOfBirth;
this.firstName = firstName;
this.lastName = lastName;
}
The problem I have as described in the title comes with the comparison section within the merge method of the mergsort algo.
Customer[] tempCus = new Customer[1000];
int c = 0;
while(i < mid && j < UpperB) {
if(customers.getFirstName[i].compareTo.(customers.getFirstName[b])<=0) {
tempCus[i] = Customer[i];
I honestly have no idea how to use the compareTo method in this situation given the construction of the class and would really appreciate a solution/ a context specific explanation or if I've gone down a bad path a bit of redirection. I have gone with what I've gone with as a bit of a shot in the dark and after multiple different attempts to get the syntax for compareTo correct. Quite confident compareTo is the correct choice, but the implementation is beyond me. Am generally unsure of how to call back a specific value in an array without the extra difficulty of the method and the bracket forrest that comes with it.
Using the in built sort() method is not an option given the task
Don't do it like that but either have Customer implement Comparable<Customer> and implement the method compareTo(Customer other) or use a Comparator<Customer> and implement the method compare(Customer left, Customer right). The implementation would be basically the same with the objects being this and other or left and right. Then compare the relevant elements one after another until you've compared all or the result is != 0.
A simple way to get a comparator would be something like this:
Comparator<Customer> comparator = Comparator.comparing( Customer:: getFirstName).thenComparing( Customer::getLastName );
Then use it like this (reusing your code so I didn't check that for correctness):
//assuming i and b are correct indices
if(comparator.compare(tempCus[i], tempCus[b])<=0) {
...
Since you want to use Comparable here's an example (think about it and expand as needed):
class Customer implements Comparable<Customer> {
public int compareTo(Customer other) {
//or: int result = this.firstName.compareTo(other.getFirstName());
int result = String.compare(this.firstName, other.getFirstName());
//0 means the strings are equal, otherwise we're done
if( result != 0 ) {
return result;
}
result = String.compare(this.lastName, other.getLastName());
//if needed add more comparisons here
return result;
}
}
Then just use it like if(tempCus[i].compareTo(tempCus[b]) <= 0)

How to Perform Percentage on item list Enum? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm looking for some tip on how to do a percentage thing for my game I want all flowers in a range of 1-98 and white/black flowers 99-100 to make it more rarerity thanks for the help :)
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1 ),
RED_FLOWERS("red", ":red:", "470419583250202644", 1),
RAINBOW_FLOWERS("rainbow", ":rainbow:", "470419602841665536", 1),
PASTEL_FLOWERS("pastel", ":pastel:", "470419629450199040", 1),
ORANGE_FLOWERS("orange", ":orange:", "470419647900942366", 1),
BLUE_FLOWERS("blue", ":blue:", "470419688753594368", 1),
BLACK_FLOWERS("black", ":black:", "470419706751352842", 1);
private final String displayName;
private final String emoticon;
private int value;
private final String id;
FlowerSuit(String displayName, String emoticon, String id, int value ) {
this.displayName = displayName;
this.emoticon = emoticon;
this.value = value;
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public String getEmoticon() {
return emoticon;
}
public String getId() {
return id;
}
public int getValue() {
// TODO Auto-generated method stub
return value;
}
}
This is how I'd do it, but it can probably be improved, for starters by using Java 8 streams etc.
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1,3),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1,2),
RED_FLOWERS("red", ":red:", "470419583250202644", 1,2),
RAINBOW_FLOWERS("rainbow", ":rainbow:", "470419602841665536", 1,2),
PASTEL_FLOWERS("pastel", ":pastel:", "470419629450199040", 1,2),
ORANGE_FLOWERS("orange", ":orange:", "470419647900942366", 1,2),
BLUE_FLOWERS("blue", ":blue:", "470419688753594368", 1,2),
BLACK_FLOWERS("black", ":black:", "470419706751352842", 1,1);
private static Random random = new Random();
private final String displayName;
private final String emoticon;
private int value;
private final String id;
private final int freq;
private FlowerSuit(String displayName, String emoticon, String id, int value, int freq ) {
this.displayName = displayName;
this.emoticon = emoticon;
this.value = value;
this.id = id;
this.freq = freq;
}
public String getDisplayName() {return displayName;}
public String getEmoticon() {return emoticon;}
public String getId() {return id;}
public int getValue() {return value;}
/**
* Choose a flower
* white has a 3 in 16 (about a 5:1) chance of being picked
* Black has a 1 in 16 chance, everything else 2/16
* #return
*/
public static FlowerSuit pick() {
//first sum all the chances (currently it's 16)
int sum = 0;
for (FlowerSuit f:FlowerSuit.values()) sum+= f.freq;
//now choose a random number
int r = FlowerSuit.random.nextInt(sum) + 1;
//now find out which flower to pick
sum = 0;
for (FlowerSuit f:FlowerSuit.values()) {
sum += f.freq;
if (r<=sum) return f;
}
//code will never get here
return FlowerSuit.WHITE_FLOWERS;
}
public static void main(final String[] args) throws Exception {
//Test it
Map<FlowerSuit,Integer>count = new HashMap<FlowerSuit,Integer>();
for (int a=0;a<1000000;a++) {
FlowerSuit f = FlowerSuit.pick();
Integer i = (count.get(f)!=null)?count.get(f):new Integer(0);
i = new Integer(i+1);
count.put(f,i);
}
int sum = 0;
for (Map.Entry<FlowerSuit,Integer>e:count.entrySet()) sum+=e.getValue();
float f = Float.valueOf(sum);
for (Map.Entry<FlowerSuit,Integer>e:count.entrySet()) {
System.out.println(e.getKey() + " was chosen " + ((e.getValue() / f) * 100f) + "% of the time");
}
}
}
gives
BLUE_FLOWERS was chosen 12.4986% of the time
PASTEL_FLOWERS was chosen 12.4707% of the time
WHITE_FLOWERS was chosen 18.7365% of the time
BLACK_FLOWERS was chosen 6.2632003% of the time
ORANGE_FLOWERS was chosen 12.4986% of the time
RED_FLOWERS was chosen 12.5241995% of the time
YELLOW_FLOWERS was chosen 12.501401% of the time
RAINBOW_FLOWERS was chosen 12.5068% of the time
You can use a TreeMap to map all of the integers from 0 to 99 to a particular FlowerSuit. Take advantage of the floorEntry method to choose a FlowerSuit for each number. It might look something like this.
public class FlowerChooser {
private static final NavigableMap<Integer, FlowerSuit> FLOWER_SUITS;
private static final Random RANDOMS = new Random();
public FlowerChooser() {
FLOWER_SUITS = new TreeMap<>();
FLOWER_SUITS.put(0, FlowerSuit.RED_FLOWERS);
FLOWER_SUITS.put(14, FlowerSuit.ORANGE_FLOWERS);
FLOWER_SUITS.put(28, FlowerSuit.YELLOW_FLOWERS);
FLOWER_SUITS.put(42, FlowerSuit.GREEN_FLOWERS);
FLOWER_SUITS.put(56, FlowerSuit.BLUE_FLOWERS);
FLOWER_SUITS.put(70, FlowerSuit.INDIGO_FLOWERS);
FLOWER_SUITS.put(84, FlowerSuit.VIOLET_FLOWERS);
FLOWER_SUITS.put(98, FlowerSuit.WHITE_FLOWERS);
FLOWER_SUITS.put(99, FlowerSuit.BLACK_FLOWERS);
}
public FlowerSuit randomFlowerSuit() {
int index = RANDOMS.nextInt(100);
return FLOWER_SUITS.floorEntry(index).getValue();
}
}
Create just one object of this class, then whenever you want a FlowerSuit, call the randomFlowerSuit method.
The randomFlowerSuit method picks a random number from 0 to 99, then finds an appropriate entry in the map. The floorEntry method chooses an entry whose key is less than or equal to the chosen number. This means that numbers from 0 to 13 get mapped to red, 14 to 27 get mapped to orange, and so on. The only number that gets mapped to white is 98, and the only number that gets mapped to black is 99.
No matter what solution you implement, you want to include a frequency measure in your enum. As an example, you can do something like this:
public enum FlowerSuit {
WHITE_FLOWERS("white", ":white:", "470419377456414720", 1, 1),
YELLOW_FLOWERS("yellow", ":yellow:", "470419561267855360", 1, 20),
// More declarations here
// Add this variable
private final int frequency;
// Do just as you did before in the constructor, but with the frequency
FlowerSuit(String displayName, String emoticon, String id, int value, int frequency){
this.frequency = frequency;
// More assignments here
}
public int getFrequency(){
return frequency;
}
// More getters here
}
This addition is critical, and no matter what method you use to weight flower selection, you will want this addition to your FlowerSuit enum.
Now, we can explore a few different ways to perform this selection.
Note 1: I use ThreadLocalRandom for random numbers in a range, which is from java.util.concurrent.ThreadLocalRandom.
Note 2: For each of these, make a single instance of FlowerPicker, and use the pickFlower() method to pick the next flower. This avoid running costly setup code over and over.
Method 1: Bag of Flowers
This method is probably the easiest to implement. It entails creating a list of enums where each is represented frequency times, and then selecting a random entry from this list. It is similar to throwing a bunch of flowers in a bag, shaking it, and then reaching your hand in and grabbing the first flower you touch. Here's the implementation:
public class FlowerPicker(){
private ArrayList<FlowerSuit> bag;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
// You can use an array here or an array list with a defined length if you know the total of the frequencies
bag = new ArrayList<FlowerSuit>();
// Add each flower from options frequency times
for (FlowerSuit flower : options)
for (int i=0; i<flower.getFrequency(); i++)
bag.add(flower);
}
public FlowerBag pickFlower(){
// Now, select a random flower from this list
int randomIndex = ThreadLocalRandom.current().nextInt(0, bag.size());
return bag.get(randomIndex);
}
}
This method has the advantage of being simple enough to understand very easily. However, it can be inefficient if your frequencies are extremely specific (like if you want a rainbow flower to be returned 499,999,999 times out of 1,000,000,000). Let's move on to the next method.
Note 1: You could make this better by reducing the fractions representing the frequency of being chosen, but I'll leave this to you.
Note 2: You could also make this slightly better by storing identification numbers, not FlowerSuit objects in the bag list.
Method 2: Navigable Map
This method is a little bit more difficult. It uses a [NavigableMap][1], which is an implementation of [TreeMap][2]. This method is fairly similar to the Bag of Flowers method, but it is a little bit more efficient. Put simply, it uses the TreeMap to give each FlowerSuit a range of numbers that can be selected to return that FlowerSuit. Here's a full example:
public class FlowerPicker(){
private NavigableMap<Double, FlowerSuit> map;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
map = new TreeMap<Double, FlowerSuit>();
int runningTotal = 0;
// Add each flower with the proper range
for (FlowerSuit flower : options){
runningTotal += flower.getFrequency();
map.put(runningTotal, flower);
}
}
public FlowerBag pickFlower(){
// Now, select a random number and get the flower with this number in its range
int randomRange = ThreadLocalRandom.current().nextInt(0, bag.size());
return map.higherEntry(randomRange).getValue();
}
}
This is a solid method, and it scales well for very specific frequencies. If you have a bunch of different types of flowers, it will be slightly worse, but this method is still a good option at large scales. There's one more option though.
Method 3: Enumerated Distribution
This method is really nice because you barely have to do anything. However, it uses [EnumeratedDistribution][3] from Apache Commons. Enumerated Distribution requires a list of pairs of objects and weights. Anyway, lets jump into it:
public class FlowerPicker(){
private EnumeratedDistribution distribution;
public FlowerPicker(){
// Get all possible FlowerSuits
FlowerSuit[] options = FlowerSuit.values();
List<Pair<FlowerSuit, Double>> weights = new List<Pair<FlowerSuit, Double>>();
// Add each flower and weight to the list
for (FlowerSuit flower : options){
weights.add(new Pair(flower, flower.getFrequency()));
// Construct the actual distribution
distribution = new EnumeratedDistribution(weights);
}
public FlowerBag pickFlower(){
// Now, sample the distribution
return distribution.sample();
}
}
This is my favorite method, simply because so much of it is done for you. Many problems like this have been solved, so why not use solutions that always exist? However, there is some value to writing the solution yourself.
In conclusion, each of these methods are perfectly fine to use at your scale, but I would recommend the second or third method.

How to format Java ArrayList with respective rows and columns and invoke the data of a column or a row?

I am a Java beginner, I have been trying to read a csv file from my computer by using Java and insert the data into a ArrayList.
public class DataRepository {
public void loadFile(){
ArrayList<String> binsGrade = new ArrayList<String>();
try {
Scanner fileScanner = new Scanner(new File("C:\\Users\\Max\\Desktop\\Grade_SampleData.csv"));
while(fileScanner.hasNextLine()){
binsGrade.add(fileScanner.nextLine());
}
fileScanner.close();
System.out.println(binsGrade);
} catch (FileNotFoundException e){
e.printStackTrace();
}
}
}
And below is the result I got:
[name,literature,math,physics,chemistry,biology,history,geology,art,sports, Michael,80,90,82,79,75,70,72,68,95, Amy,85,88,73,79,88,93,90,92,75, Johnson,72,89,81,84,83,72,89,90,82, Bob,80,81,84,89,87,90,71,65,89, Tommy,70,89,79,90,88,73,75,89,91, Rachel,90,91,80,92,87,92,95,97,87, Evonne,78,91,87,88,91,76,74,86,91]
All the records are in one row, but I actually want it to be in separated rows and columns, and for example, when I call name, I can get the value: Michael, Amy, Johson and etc. When I call literature, I can get 80, 85, 72, 80 and etc.Then I can probably use these data to do some calculation, like calculate the average, or get the maximum score and etc.
Although I have been searching online for a while, I still have not figured out the best way to achieve this. Can you please share your ideas if you have one minute? Your help will be really appreciated. Thanks!
If you want to have something implemented quickly, you can follow Srivenu comment and use a Map<String, List<String>>. Each entry of the Map will have the name as the key, and a list of string for all the results. For example to add Michael :
myMap.add("Michael", Arrays.asList({"20", "12", "8", "80"}));
Then create the different methods that will go through this map to compute the average, or find the max, etc
If you want a more oriented object approach I suggest you to create objects that will represent your data. First a result object that will contain two attributes, a string that will be the subject and an int that will be the score.
public class Result {
private String subject;
private int score;
public Result(String s, int i) {
subject = s;
score = i;
}
//Add Setters and Getters
//Add additional method if required
}
Secondly Have a Person object that wil represent someone. It will have two attributes, a String representing the name and a list of Results objects.
public class Person {
private String name;
private List<Result> results;
public Person(String s, List<Result> r) {
name = s;
results = r;
}
//Add getters and setters
//Add additional methods if required
/**
* Example of additional method
* This one will return the score for a given subject
**/
public int getScore(String subject) {
Result r = results.get(subject);
return r.getScore();
}
}
Thirdly, create a GroupOfPerson Class that will contain one attribute, a list of person. Then This class will have methods that will return the average, the max, etc...
public class GroupOfPerson {
private List<Person> persons;
public GroupOfPErson(List<Person> p) {
persons = p;
}
/**
* Example of method.
* This one will return the average score for the given subject
**/
public int getAverageForSubject(String subject) {
int average = 0;
for(Person p : persons) {
average += p.getScore(subject);
}
average /= persons.size();
return average;
}
//Add other methods
}
Finally when reading your CSV file, create the corresponding objects.

Sort class by field and by size of value [duplicate]

This question already has answers here:
sort and group a java collection
(5 answers)
Closed 8 years ago.
Good morning. I have class, which contain data in this format: [int][Object]. I never worked with classes, i usually use Lists, Maps, now i don't understand how to implement this in common classes. How to sort by field in classes?
Be careful , my toString only showing field code without field number.
I would like to sort this class by size of value[Object]
( "1 1234", "2 35881", ... "7 22" --> "7 22", "1 1234", "2 35881")
public class Record {
private int number;
private Object code;
... Getters/Setters
#Override
public String toString() {
return (String)(this.code);
}
}
public class Storage
{
List<Record> record;
public Storage(){
this.record = new ArrayList<Record>();
}
public void addRecord(Record record) {
this.record.add(record);
}
public Record getRecord(int number){
return this.record.get(number);
}
public void delRecord(int number){
this.record.remove(number);
}
public Integer sizeStorage(){
return record.size();
}
}
public class Start {
public static void main(String[] args) {
System.out.println("Start reading from Xls");
ReaderXls read = new ReaderXls();
Storage storageRZS = readrzs.ReadXls("Text1obj",2,12);
.....
System.out.println(storageRZS.getRecord(5));
System.out.println(storageRZS.getRecord(7));
System.out.println(storageRZS.getRecord(10));
2122
189266
244
The result should be this:
244
2122
189266
If you wissh to access records in an ordered way you will need to use a comparator or implement comparable in your Record class.
Sample:
Collections.sort(listOfRecords, new Comparator<Record>() {
#Override
public int compare(Record o1, Record o2) {
//null checks
/*Compare the object field according to your custom logic.
Here it is assumed that getObjectCodeAsInt() will return an integer equivalent of the objectCode.*/
if(o1.getObjectCodeAsInt() > o2.getObjectCodeAsInt())
return 1;
else if(o1.getObjectCodeAsInt() < o2.getObjectCodeAsInt())
return -1;
return 0;
}
});
You will need to make a customer Comparator for the same. Read how to sort user defined objects
I am little unsure about the exactness of the question.
However if you wish to sort the collection such as list by different class attributes (fields as you say), you may look into Collections.sort
You will need to implement the Comparator interface for each of sorting attribute.
Regards
VJ

Categories