int n = 0;
for (String s: array) {
if (s.length > 2 && mapping.containsKey(s)) n++;
}
String[] bigEnough = new String[n];
n = 0;
for (String s: array) {
if (s.length <= 2) continue;
bigEnough[n++] = mapping.get(s);
}
在 Scala 中,做同样事情最简洁的方法是:
val bigEnough = array.filter(_.length > 2).flatMap(mapping.get)