java如何去除
去除字符串中的空格
使用 trim() 方法可以去除字符串首尾的空格:
String str = " Hello World ";
String trimmed = str.trim(); // "Hello World"
去除字符串中的所有空格
使用 replaceAll() 方法结合正则表达式去除所有空格:
String str = "Hello World";
String noSpaces = str.replaceAll("\\s", ""); // "HelloWorld"
去除字符串中的特定字符
使用 replace() 方法去除指定字符:

String str = "Hello-World";
String removed = str.replace("-", ""); // "HelloWorld"
去除字符串中的重复字符
通过遍历字符串并使用 StringBuilder 去除重复字符:
String str = "aabbcc";
StringBuilder sb = new StringBuilder();
str.chars().distinct().forEach(c -> sb.append((char) c));
String result = sb.toString(); // "abc"
去除数组中的空元素
使用 Stream 过滤数组中的空值:

String[] array = {"a", "", "b", null};
String[] filtered = Arrays.stream(array)
.filter(s -> s != null && !s.isEmpty())
.toArray(String[]::new); // ["a", "b"]
去除集合中的特定元素
使用 removeIf() 方法从集合中移除符合条件的元素:
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
list.removeIf(s -> s.equals("b")); // ["a", "c"]
去除文件中的空行
使用 BufferedReader 逐行读取并过滤空行:
List<String> lines = Files.lines(Paths.get("file.txt"))
.filter(line -> !line.trim().isEmpty())
.collect(Collectors.toList());
根据具体需求选择合适的方法,确保代码简洁高效。






