Created
March 22, 2015 20:07
-
-
Save alexcrt/c83763f939129d3c4036 to your computer and use it in GitHub Desktop.
This file contains 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.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.*; | |
import java.util.function.Predicate; | |
import java.util.stream.Stream; | |
import static java.util.stream.Collectors.*; | |
public class Stats { | |
public static void main(String[] args) throws IOException { | |
List<Data> list = Files.lines(Paths.get("file")) | |
.map(s -> s.substring(1, s.length()-1).split(",")) | |
.map(arr -> new Data(Integer.parseInt(arr[0]), arr[1])) | |
.collect(toList()); | |
System.out.println(list); | |
System.out.println(ids(list, "a", i -> i < 3)); | |
Map<String, IntSummaryStatistics> stats = list.stream() | |
.flatMap(d -> d.getMap().entrySet().stream()) | |
.collect(toMap(Map.Entry::getKey, | |
e -> e.getValue().stream().mapToInt(i -> i).summaryStatistics(), | |
(i1, i2) -> {i1.combine(i2); return i1;})); | |
stats.forEach((k, v) -> System.out.println(k + " => " + v)); | |
} | |
public static Set<Integer> ids(List<Data> list, String id, Predicate<Integer> predicate) { | |
return list.stream() | |
.filter(d -> d.getMap().containsKey(id)) | |
.filter(d -> d.getMap().get(id).stream().anyMatch(predicate)) | |
.map(d -> d.getId()) | |
.collect(toSet()); | |
} | |
} | |
class Data { | |
private int id; | |
private Map<String, List<Integer>> map; | |
public Data(int id, String datas) { | |
this.id = id; | |
this.map = new HashMap<>(); | |
for(String s : datas.substring(1, datas.length()-1).split("\\|")) { | |
String[] splitted = s.split(":"); | |
this.map.merge(splitted[0], Arrays.asList(Integer.parseInt(splitted[1])), (l1, l2) -> Stream.concat(l1.stream(), l2.stream()).collect(toList())); | |
} | |
} | |
public int getId() { | |
return this.id; | |
} | |
public Map<String, List<Integer>> getMap() { | |
return this.map; | |
} | |
@Override | |
public String toString() { | |
return "Data{" + | |
"id=" + id + | |
", map=" + map + | |
'}'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment