2021年3月30日星期二

Sort ArrayList of Objects, WITHOUT Class Getters. Possible?

I'm trying to use a lambda expression to sort an ArrayList of Objects (i.e. rows imported from a CSV file), WITHOUT classes (like "Employee", or "Person", or "Animal", etc.), so there are no Getters/Setters for the Objects at all. So I'm essentially BufferedReading in rows from a CSV file, assigning them to objects, and adding those objects to an ArrayList. I want to then sort by the last value/index in each object. For example...

These are my CSV rows:

Mark,10,0,34  Tom,2,0,19  Billy,2,0,7  

...and I would like to sort them by the far right numbers in ascending order, so my sorted ArrayList would look like:

Billy,2,0,7  Tom,2,0,19  Mark,10,0,34  

Is this even possible using a lambda expression? What I have for code so far looks like this:

// Import the csv file and assign each row to a list of objects  List<Object> olReturn = null;  try (BufferedReader br = new BufferedReader(new FileReader("stats_log.csv"))) {                        olReturn = br.lines().sorted((x,y) -> x.LASTVALUEHERE() - y.LASTVALUEHERE()).collect(Collectors.toList());  } catch (FileNotFoundException e) {          e.printStackTrace();  } catch (IOException e) {          e.printStackTrace();  }                for (Object obIndObject : olReturn) {      System.out.println(obIndObject);  }  

I know how to do it if the object classes had getters for the values I want to sort by, but that doesn't apply here, so just seeing if there's a potential solution, or if it's impossible?

https://stackoverflow.com/questions/66880837/sort-arraylist-of-objects-without-class-getters-possible March 31, 2021 at 10:27AM

没有评论:

发表评论