내가 자주 사용하는 JAVA 코드 정리

개미는뚠뚠·2024년 6월 23일
0

java

목록 보기
15/15
post-thumbnail

1. 날짜와 시간

1-1. Date

    public static void main(String[] args) {
        Date now = new Date();
        
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = formatter.format(now);
        
        System.out.println("포맷된 날짜와 시간: " + formattedDate);
}

1-2. LocalDateTime

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        
        System.out.println("현재 시간: " + now);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedNow = now.format(formatter);
        
        System.out.println("포맷된 현재 시간: " + formattedNow);
    }

1-3. Instant

    public static void main(String[] args) {
        Instant now = Instant.now();
        
        System.out.println("현재 시간 (UTC): " + now);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")                                    .withZone(ZoneId.systemDefault());
        String formattedNow = formatter.format(now);
        
        System.out.println("포맷된 현재 시간 (시스템 시간대): " + formattedNow);
    }

2. API 호출

2-1. HttpURLConnection

    public static void main(String[] args) {
        try {
            URL url = new URL("API URL"); 
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json; utf-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            String jsonInputString = "전송 JSON 데이터"

            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
                String inputLine;
                StringBuilder response = new StringBuilder();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine.trim());
                }
                in.close();

                System.out.println("응답 데이터: " + response.toString());
            } else {
                System.out.println("POST 요청 실패: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2-2. OkHttp

    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();

        String url = "API URL"
        String json = "전송 JSON 데이터"

        RequestBody body = RequestBody.create(
                json,
                MediaType.get("application/json; charset=utf-8")
        );

        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                String responseData = response.body().string();
                System.out.println("응답 데이터: " + responseData);
            } else {
                System.out.println("요청 실패: " + response.code());
            }
        } catch (IOException e) {
            System.out.println("예외 발생: " + e.getMessage());
            e.printStackTrace();
        }
    }

3. JSON 데이터 다루기

3-1. JSONObject

    public static void main(String[] args) {
        // HTTP 응답으로 받은 JSON 데이터 예시
        String jsonString = "{"
                + "\"name\": \"DAEHO\","
                + "\"age\": 29,"
                + "\"city\": \"Anyang\""
                + "}";

        // JSON 문자열을 JSONObject로 변환
        JSONObject jsonObject = new JSONObject(jsonString);

        // JSONObject에서 값 얻기
        String name = jsonObject.getString("name");
        int age = jsonObject.getInt("age");
        String city = jsonObject.getString("city");

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("City: " + city);
    }

3-2. JSONArray

    public static void main(String[] args) {
        // HTTP 응답으로 받은 JSON 데이터 예시
        String jsonString = "["
                + "{ \"name\": \"DAEHO\", \"age\": 29 },"
                + "{ \"name\": \"DAEJI\", \"age\": 28 }"
                + "]";

        // JSON 문자열을 JSONArray로 변환
        JSONArray jsonArray = new JSONArray(jsonString);

        // JSONArray에서 값 얻기
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            int age = jsonObject.getInt("age");

            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
        }
    }

4. STREAM 활용하기

filter: 조건에 맞는 요소만을 걸러낸다.
map: 각 요소를 주어진 함수에 따라 변환한다.
collect: 스트림의 결과를 list, set 등의 컬렉션으로 수집한다.
forEach: 각 요소에 대해 주어진 작업을 수행한다.
reduce: 스트림의 요소를 하나의 값으로 합친다.
sorted: 요소를 정렬한다.
distinct: 중복 요소를 제거한다.
limit: 스트림의 크기를 제한한다.
skip: 처음 N개의 요소를 건너뛴다.

4-1. filter

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        List<Integer> testList = numbers.stream()
                                            .filter(n -> n % 2 == 0)  // 짝수 필터링
                                            .collect(Collectors.toList()); // 리스트로 수집

        System.out.println(testList); //짝수만 수집됨(2, 4, 6, 8, 10)
    }

4-2. map

    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        List<Integer> testArray = numbers.stream()
                .filter(n -> n % 2 == 0)  // 짝수 필터링
                .map(n -> n * n)          // 제곱
                .collect(Collectors.toList()); // 리스트로 수집

        System.out.println(testArray); //수집된 짝수들의 제곱(4, 16, 36, 64, 100)
    }

4-3. forEach

    public static void main(String[] args) {
        List<String> strings = Arrays.asList("test1", "test2", "test3", "test4", "test");

        // 모든 문자열을 대문자로 변환하고 콘솔찍기
        strings.stream()
               .map(String::toUpperCase)
               .forEach(System.out::println);
    }

5. MAP 활용하기

5-1. key 값 추출하기

    public static void main(String[] args) {

        Map<String, Object> testMap = new HashMap<>();
        
        testMap.put("name", "Daeho");
        testMap.put("age", 29);
        testMap.put("city", "Seoul");

        // keySet() 활용하여 key 값만 가져오기
        Set<String> keys = testMap.keySet();

        for (String key : keys) {
            System.out.println(key); 
        }
    }

5-2. value 값 추출하기

    public static void main(String[] args) {

        Map<String, Object> testMap = new HashMap<>();
        
        testMap.put("name", "Daeho");
        testMap.put("age", 29);
        testMap.put("city", "Seoul");

        // values() 활용하여 value 값만 가져오기
        Collection<Object> values = testMap.values();

        for (Object value : values) {
            System.out.println(value);
        }
    }

0개의 댓글