[英]Streams filter and Grouping List on Map
我正在制作一個過濾器,允許我生成一個 Map,其值是文件列表,為此,我嘗試使用 Streams。 我有以下文件列表示例:
然后我需要獲取該文件列表並將它們帶到 map 其密鑰將一個類型的所有文件分組在一個列表中;
Map <String, List < File>>:所以這將是預期的結果。
"CLA_", List <File> 3 CLA Files
"CM_", List <File> 3 CM Files
"SP_", List <File> 2 SP Files
"CON_", List <File> 2 CON Files
我有以下代碼,它只為我分組一種文件類型,CLA。 請您告訴我如何在 Map 上過濾和加載這些文件?
List<File> csvList = getFiles();
Function<File, String> filterCLA = new Function<File, String>() {
@Override
public String apply(File file) {
return String.valueOf(file.getName().startsWith("CLA_"));
}
};
Map<String, List<File>> map = csvList.stream()
.collect(groupingBy(f-> filterCLA.apply(f), toCollection(ArrayList::new)));
for(Map.Entry<String, List<File>> entry: map.entrySet()){
System.out.println(entry.getKey()+" - "+ entry.getValue());
}
此代碼僅使用CLA_
鍵將 CLA 文件保存在 map 內的列表中。 這是正確的,但我需要添加文件的 rest。
嘗試這個。 任何不以XXX_
開頭的文件名都將映射到UnknownType
類型的 catch all 鍵
List<File> csvList = List.of(
new File("CLA_FileName"),
new File("CLA_FileName"),
new File("CLA_FileName"),
new File("CM_FileName"),
new File("CM_FileName"),
new File("CM_FileName"),
new File("SP_FileName"),
new File("SP_FileName"),
new File("CON_FileName"),
new File("CON_FileName"),
new File("BadFileName1"),
new File("BadFileName2"));
// get the prefix (e.g. CM_)
Function<File, String> getPrefix = f-> {
String name = f.getName();
// location of delimiter
int index = name.indexOf('_');
if (index < 0) {
return "UNKNOWN_TYPE";
}
return name.substring(0,index+1);
};
// create the map
Map<String, List<File>> map = csvList.stream()
.collect(Collectors.groupingBy(getPrefix));
//print the map
map.entrySet().forEach(System.out::println);
印刷
UNKNOWN_TYPE - [BadFileName1, BadFileName2]
CON_ - [CON_FileName, CON_FileName]
SP_ - [SP_FileName, SP_FileName]
CM_ - [CM_FileName, CM_FileName, CM_FileName]
CLA_ - [CLA_FileName, CLA_FileName, CLA_FileName]
最后,我能夠找到過濾和分組的解決方案。 這里是代碼。 感謝大家的幫助
List<Predicate<File>> allPredicates = new ArrayList<Predicate<File>>();
allPredicates.add(str -> str.getName().startsWith("CM"));
allPredicates.add(str -> str.getName().startsWith("CLA"));
allPredicates.add(str -> str.getName().startsWith("IDP"));
allPredicates.add(str -> str.getName().startsWith("SP"));
allPredicates.add(str -> str.getName().startsWith("CON"));
return Arrays.asList(csvFiles)
.stream()
.filter(allPredicates.stream().reduce(f->true, Predicate::or))
.collect(Collectors.groupingBy(f-> f.getName().substring(0,f.getName().indexOf("_"))));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.