# HW4 ## 文件議題 * 取得一個list只有name,且不重複並排序的資料 * [Bill,Brain,KZ] ```java= @GetMapping() public List<String> getAllUserWithoutRepeatedName() { List<User> response = this.userService.getAllUser(); List<String> distinct = response.stream().map(User :: getName).distinct().sorted().collect(Collectors.toList()); return distinct; } ``` * 取得一個 map,其 key 為 ID;value 為 name * 1:"Bill" * 2:"Brian" ```java= @GetMapping() public Map<Integer, String> getAllUserWithMap() { List<User> response = this.userService.getAllUser(); Map<Integer, String> map = response.stream().collect(Collectors.toMap(User :: getId, User :: getName)); return map; } ``` * 取得第一筆 name = KZ 的資料 ```java= @GetMapping("/{name}") public User getFirstUserByName(@PathVariable String name) { List<User> response = this.userService.getAllUser(); List<User> result = response.stream().filter(x -> name.equals(x.getName())).collect(Collectors.toList()); Optional<User> first = result.stream().findFirst(); if(first.isPresent()){ User user = first.get(); return user; } else{ return null; } } ``` * 將資料先依據 age 排序,再依據 ID 排序 ```java= @GetMapping() public List<User> sortedByAgeAndId() { List<User> response = this.userService.getAllUser(); List <User> sorted = response.stream().sorted(Comparator.comparing(User :: getAge).thenComparing(User :: getId)) .collect(Collectors.toList()); return sorted; } ``` * 取得一個 string 為所有資料的 name, age|name, age * Bill, 13|KZ, 23 ```java= @GetMapping() public String getAllUserInString() { List<User> response = this.userService.getAllUser(); String result = response.stream().map(p -> p.getName()+", "+p.getAge()).collect(Collectors.joining("|")); return result; } ```