我有一个具有此结构的文件:
a, 城市1, 2013-09-05 14:08:15b, 城市2, 2015-10-08 16:10:15c, 城市2, 2010-09-05 14:08:15d, 城市1, 2011-09-05 14:08:15
它是逗号分隔的值和用行尾字符分隔的行。
我需要在 Java 8 中创建一个数据结构,其中我按城市分组行,并在每个这样的组中按日期升序排序并计算每个组中的行数。
我试过了:
- 从文件创建
List<Row>
- 创建一个按城市分组的
Map<String, List<Row>>
,并按每个组的日期排序 - 创建用于按城市和行数分组的
Map<String, Long>
这是我尝试过的代码:
public PhotoResponse processFile() {
//read each line of the file and create a new object PhotoIn for each one
List<PhotoIn> lista = null;
try {
lista = Files.lines(Paths.get(file))
.map(line -> line.split(","))
.map(photo -> new PhotoIn(photo[0].substring(0, photo[0].lastIndexOf(".")), photo[0].substring(photo[0].lastIndexOf(".") + 1 ), photo[1].trim(), parseDate(photo[2]), index++))
.collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return generateOutput(lista);
}
private PhotoResponse generateOutput(List<PhotoIn> photos) {
//Grouping photos by city
Map<String, List<PhotoIn>> photosByCity = photos.stream().collect(Collectors.groupingBy(PhotoIn::getCity));
//Sorting photos by date into each city
photosByCity.values().forEach(list -> list.sort(Comparator.comparing(PhotoIn::getDate)));
//Grouping photos by city and amount
Map<String, Long> numeroPorCiudades = photos.stream().collect(Collectors.groupingBy(PhotoIn::getCity, Collectors.counting()));
List<PhotoOut> photoOutList = new ArrayList<PhotoOut>();
photosByCity.forEach((key, list) -> {
String digits = Integer.toString(Long.toString(numeroPorCiudades.get(key)).length());
counter = 1;
list.forEach(photoIn -> {
photoOutList.add(new PhotoOut(photoIn.getName() + "." + photoIn.getExtension(), key + String.format("%0" + digits + "d", counter++) + "." + photoIn.getExtension(), photoIn.getIndex()));
});
});
return sortOutput(photoOutList);
}
我正在解决这个问题,但我正在寻找一种更好、更有效的方法来使用 Java 8 来解决这个问题。是否有可能一步完成这 3 个步骤?我需要的是将所有信息分组到一个数据结构中。
使用该模型:
class Model {
private String title;
private String city;
private LocalDateTime date;
}
可以这样完成:
List<Model> list = getFromFile();
Comparator<Model> comparator = Comparator.comparing(Model::getDate);
//grouping the list by City with lists sorted by date
Map<String, List<Model>> map = list.stream()
.collect(
Collectors.groupingBy( //grouping the list by City with lists
m -> m.getCity(),
Collectors.collectingAndThen(Collectors.toList(), l->{
l.sort(comparator);
return l;
})
)
);
//getting another map with counts
Map<String, Object> countMap = map.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().size()));