解析字符串为日期
ISO8601 格式转换
LocalDate.parse()
or LocalDateTime.parse()
String armisticeDate = "2019-0510";
LocalDate aLD = LocalDate.parse(armisticeDate);
System.out.println("Date: " + aLD);
String armisticeDateTime = "2019-0510T11:50";
LocalDateTime aLDT = LocalDateTime.parse(armisticeDateTime);
System.out.println("Date/Time: " + aLDT);
Output:
Date: 2019-0510
Date/Time: 2019-0510T11:50
自定义格式转换
DateTimeFormatter.ofPattern()
String anotherDate = "10 Apr 2019";
DateTimeFormatter df = DateTimeFormatter.ofPattern("dd MMM yyyy");
LocalDate random = LocalDate.parse(anotherDate, df);
System.out.println(anotherDate + " parses as " + random);
连接字符串或列表
加入多个字符串参数
String joinedString = String.join(", ", "How", "To", "Do", "In", "Java");
System.out.println(joinedString);
Output:
How, To, Do, In, Java
加入数组或字符串列表
List<String> strList = Arrays.asList("How", "To", "Do", "In", "Java");
String joinedString = String.join(", ", strList);
System.out.println(joinedString);
Output:
How, To, Do, In, Java
格式化输出
使用StringJoiner
类,我们可以生成连接字符串的格式化输出。这在使用lambda收集器时特别有用。
StringJoiner joiner = new StringJoiner(", ", "[", "]");
joiner.add("How")
.add("To")
.add("Do")
.add("In")
.add("Java");
Output:
[How, To, Do, In, Java]
带有Collectors.joining()的字符串的字符串列表
List<String> numbers = Arrays.asList("How", "To", "Do", "In", "Java");
String joinedString = numbers
.stream()
.collect(Collectors.joining(", ","[","]"));
System.out.println(joinedString);
Output:
[How, To, Do, In, Java]
Base64
Base 64
编码将二进制数据转换为64个可打印ASCII
字符。通常,它用于电子邮件消息和"basic"
HTTP身份验证中的二进制数据。这64个可打印的字符是:
- 26个大写字母[A … Z]
- 26个小写字母[a … z]
- 10位[0 … 9]
- 2个符号
ava 8为Base 64编码和解码目的添加了一个类,即java.util.Base64。我们将使用下面的代码示例来使用它。
1. 将字符串编码到base 64
这就像获取编码器的实例一样简单,并将字符串作为字节输入以对其进行编码。
Base64.Encoder encoder = Base64.getEncoder();
String normalString = "username:password";
String encodedString = encoder.encodeToString(
normalString.getBytes(StandardCharsets.UTF_8) );
Output:
dXNlcm5hbWU6cGFzc3dvcmQ=
2. 解码基数为64的编码字符串
这也很简单。只需获取Base64.Decoder的实例并使用它来解码基本64位编码的字符串。
String encodedString = "dXNlcm5hbWU6cGFzc3dvcmQ=";
Base64.Decoder decoder = Base64.getDecoder();
byte[] decodedByteArray = decoder.decode(encodedString);
//Verify the decoded string
System.out.println(new String(decodedByteArray));
Output:
username:password
3. 换行到基本64编码的输出流
如果您不想直接使用数据而宁愿使用流,则可以包装输出流,以便写入此输出流的所有数据将自动进行64位编码。
Path originalPath = Paths.get("c:/temp", "mail.txt");
Path targetPath = Paths.get("c:/temp", "encoded.txt");
Base64.Encoder mimeEncoder = Base64.getMimeEncoder();
try(OutputStream output = Files.newOutputStream(targetPath)){
//Copy the encoded file content to target file
Files.copy(originalPath, mimeEncoder.wrap(output));
//Or simply use the encoded output stream
OutputStream encodedStrem = mimeEncoder.wrap(output);
}
精确算术支持
- Math.multiplyExact
- Math.addExact
Math.floorMod(``10
, ``2``)
Math.nextDown(``100``)
参考:https://howtodoinjava.com/java8/java-8-exact-airthmetic-operations-supported-in-math-class/
比较器
快速参考:
//Compare by Id
Comparator<Employee> compareById_1 = Comparator.comparing(e -> e.getId());
Comparator<Employee> compareById_2 = (Employee o1, Employee o2) -> o1.getId().compareTo( o2.getId() );
//Compare by firstname
Comparator<Employee> compareByFirstName = Comparator.comparing(e -> e.getFirstName());
//how to use comparator
Collections.sort(employees, compareById);
按名字排序-顺序
List<Employee> employees = getEmployees();
//Sort all employees by first name
employees.sort(Comparator.comparing(e -> e.getFirstName()));
//OR you can use below
employees.sort(Comparator.comparing(Employee::getFirstName));
按名字排序-逆序
List<Employee> employees = getEmployees();
//Sort all employees by first name; And then reversed
Comparator<Employee> comparator = Comparator.comparing(e -> e.getFirstName());
employees.sort(comparator.reversed());
多字段排序
List<Employee> employees = getEmployees();
//Sorting on multiple fields; Group by.
Comparator<Employee> groupByComparator = Comparator.comparing(Employee::getFirstName)
.thenComparing(Employee::getLastName);
employees.sort(groupByComparator);
System.out.println(employees);
并行排序(多线程)
上千会很快。
//Parallel Sorting
Employee[] employeesArray = employees.toArray(new Employee[employees.size()]);
//Parallel sorting
Arrays.parallelSort(employeesArray, groupByComparator);
System.out.println(employeesArray);
正则表达式做谓词
将Regex转换为谓词
我有不同域的电子邮件列表,我想只对域名为“example.com”的电子邮件ID执行某些操作。
现在使用[Pattern.compile().asPredicate()](https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#asPredicate--)
方法从编译的正则表达式中获取谓词。此谓词可以与lambda流一起使用,以将每个标记应用到流中。
public class RegexPredicateExample {
public static void main(String[] args) {
// Compile regex as predicate
Predicate<String> emailFilter = Pattern
.compile("^(.+)@example.com$")
.asPredicate();
// Input list
List<String> emails = Arrays.asList("alex@example.com", "bob@yahoo.com",
"cat@google.com", "david@example.com");
// Apply predicate filter
List<String> desiredEmails = emails
.stream()
.filter(emailFilter)
.collect(Collectors.<String>toList());
// Now perform desired operation
desiredEmails.forEach(System.out::println);
}
}
输出:
alex@example.com
david@example.com
老方式是使用:Pattern.matcher()