---
# System prepended metadata

title: homework

---

# homework

## 實作Part4

- 取得一個 list 只有 name，且不重複並排序的資料

  - [Bill, Brian, KZ]

```java!
    public List<String> getList() {
        List<User> response = userRepository.findAll();
        List<String> namelist = new ArrayList<>();
        List<String> namelist1 = new ArrayList<>();
        for (User user : response) {
            namelist.add(user.getName());
        }
        namelist1 = namelist.stream()
                .distinct()
                .sorted()
                .collect(Collectors.toList());
        return namelist1;
    }

```

- 取得一個 map，其 key 為 ID；value 為 name

  - 1 : “Bill”
  - 2 : “Brian”

```java=
public Map<Integer,String> getMap(){
    List<User> response = userRepository.findAll();
    Map<Integer,String> response1 = response.stream()
        .collect(Collectors.toMap(e -> e.getId(),e -> e.getName()));
    return response1;
}
```

- 取得第一筆 name = KZ 的資料

```java=
public Optional<User> getFirst(){
   List<User> response = userRepository.findAll();
   String name = "KZ";
   Optional<User> response1 = 
   response.stream()
       .filter(e -> e.getName().equals(name))
       .findFirst();
   return response1;
}
```

- 將資料先依據 age 排序，再依據 ID 排序

```java=
public List<User> getUser() {
    List<User> response = userRepository.findAll()
        .stream()
            .sorted(Comparator.comparing(User::getAge)
                    .reversed().thenComparing(User::getId))
            .collect(Collectors.toList());
    return response;
}
```

- 取得一個 string 為所有資料的 name, age|name, age

  - Bill, 13|KZ, 23

```java=
public String getAll() {
    String response = userRepository.findAll()
        .stream()
        .map(e -> e.getName() + "," + e.getAge())
        .collect(Collectors.joining("|"));
    return response;
}
```
