Created
February 14, 2019 19:59
-
-
Save deltastateonline/f20dbb76579f51355a9ce80807afd559 to your computer and use it in GitHub Desktop.
Using apache commons csv and java 8 lambda functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.adjustit.csv; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.InputStreamReader; | |
import java.io.Reader; | |
import java.util.List; | |
import java.util.function.Consumer; | |
import java.util.function.Predicate; | |
import org.apache.commons.csv.CSVFormat; | |
import org.apache.commons.csv.CSVParser; | |
import org.apache.commons.csv.CSVRecord; | |
/** | |
* Hello world! | |
* | |
*/ | |
public class App | |
{ | |
public static void main( String[] args ) | |
{ | |
System.out.println( "Hello World!" ); | |
try { | |
parseCSVSort("resources/booking_integration_logs.csv"); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
System.out.println("Done"); | |
} | |
public static List<CSVRecord> getRecords2(String fname) throws IOException{ | |
InputStream initialStream = App.class.getClassLoader().getResourceAsStream(fname); | |
// get the | |
Reader in = new InputStreamReader(initialStream); | |
// create the formater | |
CSVFormat ourFormater = CSVFormat.RFC4180.withIgnoreSurroundingSpaces().withFirstRecordAsHeader(); | |
// put it into the paser | |
CSVParser ourParser = new CSVParser(in, ourFormater); | |
List<CSVRecord> records = null; | |
try { | |
records = ourParser.getRecords(); | |
} catch (IOException e) { | |
// TODO Auto-generated catch block | |
e.printStackTrace(); | |
} | |
return records; | |
} | |
public static void parseCSVSort(String fname) throws IOException{ | |
List<CSVRecord> records = getRecords2(fname); | |
Consumer<CSVRecord> printAll = e -> System.out.printf("BookingId :%s\t Howmany: %s\n",e.get("bookingId"), e.get("howmany")); | |
// filter by the number of howmany | |
Predicate<CSVRecord> howmany = (p) -> (Integer.valueOf(p.get("howmany")) > 10); | |
System.out.println("Print All Data "); | |
records.stream().filter(howmany).forEach(printAll); | |
} | |
} |
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-csv</artifactId> <version>1.6</version> </dependency>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add sorting
`public static void parseCSVSort(String fname) throws IOException{