-3

I know this is not a new question but I want to sort CSV file by Column preferred in java8.

The Data-structure of CSV is List<List<CsvEntity> I need to sort first by one field of the CsvEntity then by other (not must) example by: firstName then by lastName.

class CsvEntity{
   private String firstName
   private String lastName
   private String address
}

Following this - How to sort data in a CSV file using a particular field in Java?

What modifications do I need to make for supporting sort on multiple keys in Java8?

Naman
  • 27,789
  • 26
  • 218
  • 353
VitalyT
  • 1,671
  • 3
  • 21
  • 49

2 Answers2

2

Just use comparator, an example of sorting by firstName then by lastName

list.forEach(l -> l.sort(Comparator.comparing(CsvEntity::getFirstName)
                               .thenComparing(CsvEntity::getLastName)));

Of course you have to have getters for your fields to use method reference

Schidu Luca
  • 3,897
  • 1
  • 12
  • 27
0
        final Function<CsvEntity, String> byfirstName = CsvEntity -> CsvEntity.getfirstname();
        final Function<CsvEntity, String> bylastname = CsvEntity -> CsvEntity.getlastname();
        final Function<CsvEntity, String> byaddress = CsvEntity -> CsvEntity.getaddress(); 
        System.out.println("Sorted in ascending order by Firstname and Lastname: ");
        List<CsvEntity> sortedlist =   CsvEntity.stream()
            .sorted(Comparator.comparing(byfirstName).thenComparing(bylastname))
            .collect(Collectors.toList());
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55