3 Mayıs 2023 Çarşamba

Matcher.results metodu

Giriş
İmzası şöyle
Stream<MatchResult> results()
Java 9 ile geliyor. Matcher.find() çağrısını döngü içinde yapmak yerine Strema ile kullanmayı kolaylaştırıyor

Örnek
Şöyle yaparız. Burada eski kodlarda Matcher.find() sonucu bir liste içinde toplanıyor sonra işleniyor. Yeni kodlardaysa Matcher.results() direkt Stream döndürüyor
var str = """
List<String> results = stream
  .filter(s -> pattern.matcher(s).matches()).toList();
""";

Matcher m = Pattern.compile("[\\p{L}]+").matcher(str); // letters

// Eski kod
var words = new LinkedList<>();
while (m.find()) {
  words.add(m.group());
}

System.out.println(words);
// [List, String, results, stream, filter, s, pattern, matcher, s, matches, toList]

m.reset();

// Yeni kod
var words2 = m.results().map(MatchResult::group).toList();

System.out.println(words2);
// [List, String, results, stream, filter, s, pattern, matcher, s, matches, toList]


Hiç yorum yok:

Yorum Gönder