---
# System prepended metadata

title: 8/19回家作業

---

# 8/19回家作業

1.使用 findAll() 將 user 資料從 DB 撈出後，使用 stream 進行操作以及過濾
- 取得一個 list 只有 name，且不重複並排序的資料
    - UserService
```java = 
public List<String> getUniqueUser() {
        List<String> nameList = new ArrayList<>();
        List<String> nameList1 = new ArrayList<>();
        List<User> userList1 = userRepository.findAll();
        for (User user : userList1) {
            nameList.add(user.getName());
        }
        nameList1 = nameList.stream().distinct().sorted().collect(Collectors.toList());
        return nameList1;
    }
```
- 取得一個 map，其 key 為 ID；value 為 name
    - UserService
```java = 
public Map<Integer, String> getUserIdNameMap() {
        List<User> userList = userRepository.findAll();
        Map<Integer, String> userIdNameMap = new HashMap<>();
        userList.stream()
                .forEach(e -> userIdNameMap.put(e.getId(), e.getName()));
        return userIdNameMap;
    }
```

- 取得第一筆 name = KZ 的資料
    - UserService
```java = 
public User getFirstMatchByName(String name) {
        List<User> userList1 = userRepository.findAll();
        System.out.println(name);

        List<User> filteredUsers = userList1.stream().filter(x -> x.getName().equals(name)).collect(Collectors.toList());
        if (!filteredUsers.isEmpty()) {
            return filteredUsers.get(0);
        }

        System.out.println("No such user");
        return null;
    }
```

- 將資料先依據 age 排序，再依據 ID 排序
    - Userrepository
```java = 
 @Query(value = "SELECT * FROM member ORDER BY Age ASC, Id ASC", nativeQuery = true)
    List<User> findUserOrderByNameAndAge();
```
    - UserService
```java = 
public List<User> findUserOrderByNameAndAge() {
        List<User> userList1 = userRepository.findUserOrderByNameAndAge();
        return userList1;
    }
```
- 取得一個 string 為所有資料的 name, age|name, age
    - UserService
```java = 
    public String FindUserNameAndAge() {
        List<User> userList1 = userRepository.findAll();
        List<String> nameAndAge = new ArrayList<>();
        for (User user : userList1) {
            nameAndAge.add(user.getName() + ", " + user.getAge());
        }
        String allUserNameAndAge = String.join("|", nameAndAge);
        return allUserNameAndAge;
    }
```
- 閱讀文件連結
    - lombok @Builder
https://matthung0807.blogspot.com/2019/11/lombok-builder.html
    - Spring Data JPA Specification
    https://matthung0807.blogspot.com/2021/06/spring-data-jpa-specification-dynamic-query.html
    https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/
    - 未實現損益
    https://rich01.com/calculate-stock-gain-and-loss/