Last active
November 9, 2017 09:32
-
-
Save dmengelt/92a22649a14e28ce1aba to your computer and use it in GitHub Desktop.
group values of list of key values pairs
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
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.AbstractMap.SimpleEntry; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
public class Grouper { | |
public static void main(String[] args) { | |
if(args == null || args.length == 0) { | |
System.out.println("Usage: java -cp <your-java-cp> Grouper file.csv"); | |
System.exit(0); | |
} | |
try (Stream<String> lines = Files.lines(Paths.get(args[0]))) { | |
lines.map(l -> l.split(",")) | |
.map(l -> new SimpleEntry<>(l[0], Double.parseDouble(l[1]))) | |
.collect(Collectors.groupingBy(SimpleEntry::getKey, | |
Collectors.averagingDouble(SimpleEntry::getValue))) | |
.entrySet() | |
.stream() | |
.map(e -> e.getKey() + "=" + String.format("%.4f", e.getValue())) | |
.forEach(System.out::println); | |
} catch (Exception e) { | |
System.out.println("An error occurred! " + e.getMessage()); | |
System.out.println("Please make sure your key/value pairs have the following format: /my/string,13.37"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've got a NPE in line 11. Why?? Plesse advice