博文

目前显示的是标签为“Set”的博文

PHP8 —— New String Helpers

新增了三个字符串函数,str_starts_with, str_ends_with, str_contains, PHP 的函数这么方便,很难想象竟然一直没有这几个。 str_starts_with 判断字符串是否以另一个字符串开头,在PHP7以及之前 $id = 'inv_abcdefgh'; $result = strpos($id, 'inv_') === 0; var_dump($result); // true PHP8 中可以直接这么写 $result = str_starts_with($id, 'inv_'); str_ends_with 判断字符串是否以另外一个字符串结尾,在 PHP7 及之前,比较麻烦,通常是这么写 $id = 'abcd_inv'; $result = strpos(strrev($id), strrev('_inv')) === 0; 或者 $result = substr($id, -1 * strlen('_inv')) === '_inv'; 或者上正则吧 $result = preg_match('/_inv$/', $id) === 1; 看起来都是比较麻烦的。PHP8 里面可以简化成下面这样了 $id = 'abcd_inv'; $result = str_ends_with($id, '_ind'); str_contains 字符串包含,PHP8 之前一般就是 strpos 来实现了 $url = 'https://example?for=bar'; $result = strpos($url, '?') !== FALSE; PHP8 就直接一点 $result = str_contains($url, '?');

Java学习笔记 —— Java 8 中 List 和 Set 新方法

Java 8 在List和Set接口中引入了几种方法: removeIf 删除满足条件的元素。 所有实现List或Set的类均可用。 replaceAll在List上可用,并使用(UnaryOperator)替换元素功能。 sort在List接口上可用,对列表本身进行排序。 与Steam操作不同,它们会更改集合本身,而Steam操作会产生新的复制结果。 removeIf 举个🌰,下面的代码删除数字开头的事物: for (Transaction transaction : transactions) { if(Character.isDigit(transaction.getReferenceCode().charAt(0))) { transactions.remove(transaction); } } 上面的写法可能会导致ConcurrentModificationException。如果我们使用下面代码,通过for-each循环使用Iterator对象: for (Iterator<Transaction> iterator = transactions.iterator(); iterator.hasNext(); ) { Transaction transaction = iterator.next(); if(Character.isDigit(transaction.getReferenceCode().charAt(0))) { transactions.remove(transaction); } } 注意下面两种独立的管理集合操作: Iterator 对象, 使用next() 和 hasNext() 访问元素 Collection 对象本身, 使用 remove() 删除元素 Iterrator的状态不再与集合的状态同步,反之亦然。 要解决此问题,我们必须显式使用Iterator对象并调用其remove()方法: for (Iterator<Transaction> iterator = transactions.iterator(); iterator.hasNext(); ) { ...