Jdk8的stream使用
1. Map操作:
获取map的key或者value放到list:
private static void getMapKeyOrValueToList() { Map<String, Object> map = new HashMap<>(); map.put("math", 96); map.put("english", 89); map.put("chanises", 90); map.put("phycicl", 86.5); // 获取所有的key to list<> List<String> list = map.keySet().stream().collect(Collectors.toList()); System.out.println("map key to list :" + list); // 获取所有的key to set<> Set<String> set = map.keySet().stream().collect(Collectors.toSet()); System.out.println("map key to set :" + set); }
map将某个字段值转成大小写:
private static void mapToLower() { List<String> lines = Arrays.asList("Spring", "node", "mkyong", "erer"); // 法一 lines = lines.stream().map(String::toLowerCase).collect(Collectors.toList()); System.out.println("toLowerCase:" + lines); // 法二 lines = lines.stream().map(m -> m.toLowerCase()).collect(Collectors.toList()); System.out.println("toLowerCase:" + lines); lines = lines.stream().map(String::toUpperCase).collect(Collectors.toList()); System.out.println("toUpperCase:" + lines); }
2.List操作:
list分页:
private static void ListPages(int pageRows, int pageIndex) { List<String> persons = new ArrayList(); for (int i = 1; i <= 10000; i++) { persons.add("name" + i); } //use stream() of skip() and limit() List<String> result = persons.stream().skip((pageRows * (pageIndex - 1))).limit(pageRows).collect(Collectors.toList()); System.out.println("--------" + result); }
list过滤+排序:
private static void ListFilterAndSort() { List<String> lines = Arrays.asList("spring", "node", "mkyong", "erer"); List<String> result1 = lines.stream() // convert list to stream .filter(line -> !"mkyong".equals(line)) // filter the line which equals to "mkyong" .sorted((s1, s2) -> s1.compareTo(s2)).collect(Collectors.toList()); // collect the output and convert streams to a list result1.forEach(System.out::println); }
list去重+求和:
private static void ListDistinct() { List<String> lines = Arrays.asList("spring", "node", "mkyong", "erer", "node"); System.out.println("去重:" + lines.stream().distinct().collect(Collectors.toList())); System.out.println("过滤:" + lines.stream().filter(line -> !"mkyong".equals(line)).collect(Collectors.toList())); // String tString = "我认为#我认为#沃尔沃若"; // Stream<String> ssStream = Stream.of(tString.split("#")).peek(System.out.print(tString)); List<Integer> nums = Arrays.asList(1, 1, null, 2, 3, 4, null, 5, 6, 7, 8, 9, 10); System.out.println("求和:" + nums.stream().filter(num -> num != null).distinct().mapToInt(num -> num * 2) .peek(System.out::println).skip(2).limit(4).sum()); // System.out.println("sum is:" + nums.stream().filter(i -> System.out.println("hello" + // i)).reduce().get());
}