您可以在
Collector
中执行匹配操作:
Map<String,Set<String>> map=Files.lines(filePath)
.collect(HashMap::new,
(hm,line)-> {
Matcher m=emailPattern.matcher(line);
if(m.matches())
hm.computeIfAbsent("mail", x->new HashSet<>()).add(line);
else if(m.usePattern(urlPattern).matches())
hm.computeIfAbsent("url", x->new HashSet<>()).add(line);
},
(m1,m2)-> m2.forEach((k,v)->m1.merge(k, v,
(s1,s2)->{s1.addAll(s2); return s1;}))
);
Set<String> mail=map.get("mail"), url=map.get("url");
请注意,这可以轻松地适应在一行内查找多个匹配项。
Map<String,Set<String>> map=Files.lines(filePath)
.collect(HashMap::new,
(hm,line)-> {
Matcher m=emailPattern.matcher(line);
while(m.find())
hm.computeIfAbsent("mail", x->new HashSet<>()).add(m.group());
m.usePattern(urlPattern).reset();
while(m.find())
hm.computeIfAbsent("url", x->new HashSet<>()).add(m.group());
},
(m1,m2)-> m2.forEach((k,v)->m1.merge(k, v,
(s1,s2)->{s1.addAll(s2); return s1;}))
);
Stream<String> fileStream = Files.lines(Paths.get("test")); fileStream.//匹配电子邮件 fileStream.//匹配URL
当你的问题是不想创建两个流时,我能想到的唯一解决方案。 - LokiList
中并遍历两次不算是一个合格的解决方案,对吗? - Tagir ValeevList
中,并进行两次遍历,这似乎是我能想到的最好的解决方案。 - Voidpaw