博文

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

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学习笔记 —— 给Map排序

Map接口包含一个称为Map.Entry的公共、静态、内部接口,该接口表示键值对。 Map.entrySet方法返回一组Map.Entry元素。 在Java 8之前,给map排序时主要使用接口中的getKey和getValue方法。 Java8 中,增加了下表中的静态方法。 方法 描述 comparingByKey(Comparator<? super K> cmp) Returns a comparator that comparesMap.Entryby key using the givenComparator comparingByValue() Returns a comparator that comparesMap.Entryin natural order on value comparingByValue(Comparator<?superV>cmp) ReturnsacomparatorthatcomparesMap.Entryby value using the givenComparator 下面用计算字典中单词长度和数量映射,来说明怎么使用这些方法。 Unix系统在 /usr/share/dict/words 目录中包含一个文件,保存了Webster第二版词典的内容。 我们用 Files.lines方法读取文件行并生成包含这些行的字符串流。 System.out.println("\nNumber of words of each length:"); try (Stream<String> lines = Files.lines(dictionary)) { lines.filter(s -> s.length() > 20) .collect(Collectors.groupingBy( String::length, Collectors.counting())) .forEach((len, num) -> System.out.printf("%d: %d%n", len, num)); } catch (IOException e) {...

Java学习笔记 —— Java 8 Map 新特性

Java 8引入了Map接口支持的几种默认方法。 我们从forEach开始介绍。 forEach 旧版Java遍历Map的键和值一直很尴尬,需要在Map上使用Map.Entry 的迭代器: for(Map.Entry<String, Integer> entry: ageOfFriends.entrySet()) { String friend = entry.getKey(); Integer age = entry.getValue(); System.out.println(friend + " is " + age + " years old"); } 从Java 8开始,Map接口支持forEach方法,该方法接受BiConsumer,并将键和值作为参数。 使用forEach可以让代码更为简洁: ageOfFriends.forEach((friend, age) -> System.out.println(friend + " is " + age + " years old")); Java 8引入了两种便捷的方法来比较Map中的条目,可以按值或键对Map进行排序: Entry.comparingByValue Entry.comparingByKey 以下代码: Map<String, String> favouriteMovies = Map.ofEntries(entry("Raphael", "Star Wars"), entry("Cristina", "Matrix"), entry("Olivia","James Bond")); favouriteMovies .entrySet() .stream() .sorted(Entry.comparingByKey()) .forEachOrdered(System.out::println); 的输出为: Cristina=Matrix Oliv...