Java
  • List 1) Arrays.asList : 요소 갱신은 가능하나, 추가/삭제할 수 없다. /* List */ List testList = Arrays.asList("AAA", "BBB", "CCC"); testList.set(0, "DDD"); // 갱신은 가능하다. // testList.add("DDD"); // 고정 리스트로, 요소를 추가/삭제 할 수 없다. 2) HashSet(Arrays.asList()) // 리스트를 인수로 받는 HashSet 생성자를 사용하여 생성할 수 있다. Set testSetList = new HashSet(Arrays.asList("AAA", "BBB", "CCC")); testSetList.add("DDD"); 3) List.of 팩토리 메소드 : 리스트를 변경할 수 ..

    Read more
  • 샘플 리스트 // sample List List products = Arrays.asList( new Product(0, "Note_red", 1, 100), new Product(1, "Note_blue", 2, 200), new Product(2, "Note_green", 3, 300), new Product(3, "Note_pink", 4, 400), new Product(4, "Note_yellow", 5, 500), new Product(5, "Note_black", 6, 600), new Product(6, "Note_white", 7, 700), new Product(7, "Note_purple", 8, 800) ); 요약 Collectors.coutning() /* Collectors 의 ..

    Read more
  • 평면화 FlatMap List의 요소에 속하는 모든 고유문자를 리스트로 리턴받고 싶다. 아래의 과정을 걸쳐서 스트림 평면화를 진행하는 flatMap을 이해해보자. 우선, 우리가 하고싶은 상황은 아래와 같다. 이전: "AAA", "BBB", "CCC" 이후: "A", "A", "A", "B", "B", "B", "C", "C", "C" 과정1. Map 사용 // sample List List wordList = Arrays.asList( "AAA", "BBB", "CCC" ); /* 원하는 결과 : List / 결과 : List */ List productNameList = wordList.stream() .map(word -> word.split("")) .collect(Collectors.toList(..

    Read more
  • 샘플 파일 생성 1) Product.java public class Product { private int idx; private String productName; private int ordCnt; private int totalCnt; public int getIdx() { return idx; } public String getProductName() { return productName; } public int getOrdCnt() { return ordCnt; } public int getTotalCnt() { return totalCnt; } public Product(int idx, String productName, int ordCnt, int totalCnt) { this.idx = i..

    Read more
  • 배열 Array를 역순 정렬하기 Arrays.sort(arr, Collections.reverseOrder());

    Read more
  • Stream 사용하여 배열 array의 max, min 구하기 1) max int arrayMax = Arrays.stream(arr).max().getAsInt(); 2) min int arrayMin = Arrays.stream(arr).min().getAsInt();

    Read more
  • 기존 코드 관리 보통 프로젝트를 진행하면서, 관리되는 코드 등은 static final 변수로 선언되어있다. public class CommonStatus { public static final int CODE = 200; public static final String MESSAGE = "성공"; } static final 변수를 Enum 으로 변환해보자. Enum.java public enum EnumCode { /** Default Code */ MESSAGE ("성공") ; @Getter private final String code; EnumCode(String code) { this.code = code; } } 호출 코드 TestDto testDto = new TestDto(); testDt..

    Read more
  • 특정날짜와 format을 파라미터로 설정하여 해당 format에 맞게 어제 일자 조회 public static String getYesterday(String paramDate, String format) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format); LocalDate currentDate = LocalDate.parse(paramDate, formatter); return currentDate.minusDays(1).format(formatter); }

    Read more
  • 현재날짜(LocalDate.now())가 올해의 몇번째 주차인지 조회 public static String getWeekOfYear() { LocalDate currentDate = LocalDate.now(); int weekOfYear = currentDate.get(WeekFields.ISO.weekOfYear()); return Integer.toString(weekOfYear); }

    Read more
  • case 목록 case1. 현재날짜를 년-월 yyyyMM 포맷으로 조회 public static String getCurrentYearMonth() { LocalDate currentDate = LocalDate.now(); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM"); return currentDate.format(formatter); } case2. 받아온 날짜를 매개변수 format(yyyy-MM-dd, yyyyMM 등) 포맷으로 조회 public static String getDateFormat(String date, String format) { DateTimeFormatter formatter = DateTimeFor..

    Read more
  • 상황분석 우리에게 운영중인 레거시 프로젝트가 있다고 가정해보자. 그리고 UserDto 파일이 존재하는데, 해당 Dto 파일은 User 테이블의 필드들을 담고있는 클래스이다. UserDto.java public class UserDto implements CommonUser { private String name; private String gender; private String age; public UserDto(String name, String gender, String age) { this.name = name; this.gender = gender; this.age = age; } @Override public String getName() { return name; } @Override pub..

    Read more
  • Call by Value 값에 의한 호출 public class Main { public static void main(String[] args) { int a = 1; int b = 2; System.out.println(a); // 1 System.out.println(b); // 2 Main main = new Main(); main.update(a); System.out.println(a); // 1 System.out.println(b); // 2 } void update(int a) { /* 지역변수 처럼 */ a = 5; System.out.println(a); // 5 } } 변수 a, b에 각각 1, 2를 할당했다. 그리고 변수를 출력해보면 a = 1, b = 1로 출력된다. 그리고 up..

    Read more
  • 함수형 인터페이스 제공 람다 표현식을 쓸 수 있는 인터페이스는 오직 public 메서드 하나만 가지고 있는 인터페이스여야한다. 자바 8에서 이러한 인터페이스를 특별히 함수형 인터페이스라고 부르고, 함수형 인터페이스에서 제공하는 단 하나의 추상 메서드를 함수형 메서드라고 부른다. 인터페이스를 사용해야하는 개발자 입장에서 람다 표현식을 사용하기 위해 메서드가 하나뿐인 인터페이스를 제공해야하는 번거로움을 해결하기 위해 함수형 인터페이스를 만들고 java.util.function 패키지로 제공하고있다. 아래 예제 github 주소 : https://github.com/westssun/practicalJava8/tree/master/src/main/java/ch4/%EB%9E%8C%EB%8B%A4%EC%99%80..

    Read more
  • 소스코드 : https://github.com/westssun/moderninjava8/tree/master/src/main/java/ModernInJava8/ch4_5_6_stream GitHub - westssun/moderninjava8: [BOOK] 모던 인 자바8 [BOOK] 모던 인 자바8. Contribute to westssun/moderninjava8 development by creating an account on GitHub. github.com 예제 실행을 위한 DTO @Data public class SampleDto { private int idx; private String name; private String gender; } 1) 스트림 기본 /** * 기존 Java7 코..

    Read more
  • 상황 TestDto testDto = testList.get(0); 자바 List의 0번째 데이터를 set 해줘야하는 코드를 만났다. testList에는 어떤 데이터가 들어있는지 모른다. (null 일수도있고, 몇개의 row가 들어가있을 수 있다.) 위 testList.get(0) 을 실행하는 부분에서 NullPointerException을 만났다. 분석 NullPointerException이 발생하여 null 체크를 추가하였다. testList는 외부 API에서 얻어온 데이터가 들어있는 List라서 어느 특정 실행 시점에서 null인 testList에 get 메서드를 호출했기 때문에 발생하는 문제였다. if (testList != null) { TestDto testDto = testList.get(0..

    Read more
  • Copyright 2024. GRAVITY all rights reserved