英文:
How to convert this big code to Java 8 lambda expressions
问题
我只会翻译代码部分,以下是代码的中文翻译:
public class charFile {
public static void main(String args[]) {
TreeMap<Character, Integer> hashMap = new TreeMap<Character, Integer>();
File file = new File("new.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file, "utf-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (scanner.hasNext()) {
char[] chars = scanner.nextLine().toLowerCase().toCharArray();
for (Character c : chars) {
if (!Character.isLetter(c)) {
continue;
} else if (hashMap.containsKey(c)) {
hashMap.put(c, hashMap.get(c) + 1);
} else {
hashMap.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
希望这有助于你更好地理解这段代码。
英文:
Im just new in java lambda and i struggling to make this code in lambda form please can someone at least tell me how to do it in big codes like this one
or should i use streams to make it easier and thx.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
public class charFile {
public static void main(String args[]) {
TreeMap<Character, Integer> hashMap = new TreeMap<Character, Integer>();
File file = new File("new.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file, "utf-8");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (scanner.hasNext()) {
char[] chars = scanner.nextLine().toLowerCase().toCharArray();
for (Character c : chars) {
if (!Character.isLetter(c)) {
continue;
} else if (hashMap.containsKey(c)) {
hashMap.put(c, hashMap.get(c) + 1);
} else {
hashMap.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : hashMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
答案1
得分: 4
Files.lines(Paths.get("new.txt"), StandardCharsets.UTF_8)
.map(String::toLowerCase)
.flatMapToInt(String::chars)
.mapToObj(c -> (char)c)
.filter(Character::isLetter)
.collect(Collectors.groupingBy(c -> c, TreeMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + ": " + v));
英文:
Files.lines(Paths.get("new.txt"), StandardCharsets.UTF_8)
.map(String::toLowerCase)
.flatMapToInt(String::chars)
.mapToObj(c -> (char)c)
.filter(Character::isLetter)
.collect(Collectors.groupingBy(c -> c, TreeMap::new, Collectors.counting()))
.forEach((k, v) -> System.out.println(k + ": " + v));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论