Skip to content

Instantly share code, notes, and snippets.

@dmengelt
Last active November 9, 2017 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmengelt/92a22649a14e28ce1aba to your computer and use it in GitHub Desktop.
Save dmengelt/92a22649a14e28ce1aba to your computer and use it in GitHub Desktop.
group values of list of key values pairs
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");
}
}
}
@openwms
Copy link

openwms commented Nov 24, 2014

I've got a NPE in line 11. Why?? Plesse advice

@dmengelt
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment