Java
  • 가비지 컬렉션 (Garbage Collection) 유효하지 않은 메모리(Garbage)를 자동으로 제거해주는 작업이다. Java Appliation은 JVM(Java Virtual Machine)위에서 구동되는데, JVM의 기능 중 더이상 사용하지 않는 객체를 청소하여 메모리 공간을 확보하는 작업이다. GC가 필요한 이유는? Heap 영역에 저장되는 객체들이 계속해서 쌓이게되면 OutOfMemoryException이 발생하여, 이를 방지하기 위해 주기적으로 사용하지 않는 객체를 수집하여 제거해줘야한다. 예제 Test test = new Test(); test.setId(1L); test.setName("seohae"); testRepository.save(test); test = null; // 더이상..

    Read more
  • Stream 코드 /* num sum */ int numSum = param.chars() .filter(Character::isDigit) .map(a -> Character.digit(a, 10)) .sum(); 결과 param = "K1C57PQR" numSum = 13 (1 + 5 + 7)

    Read more
  • Stream 코드 String chars = param.chars() .sorted() .mapToObj(ch -> (char) ch) // Stream .filter(ch -> !Character.isDigit(ch)) .map(Object::toString) .collect(Collectors.joining()); 각 단계별로 Stream 형태 확인 결과 param = "AC2B332" chars = "ABC"

    Read more
  • Stream 코드 private static void getPairs() { List numbersA = Arrays.asList(1, 2, 3); List numbersB = Arrays.asList(4, 5); List pairs = numbersA.stream() .flatMap(i -> numbersB.stream() .map(j -> new int[]{i, j})) .collect(toList()); for (int[] a : pairs) { System.out.println(Arrays.toString(a)); } } 결과 [1, 4] [1, 5] [2, 4] [2, 5] [3, 4] [3, 5]

    Read more
  • TreeMap TreeMap이란, 이진트리를 기반으로 한 Map 컬렉션이다. TreeMap 은 아래와 같이 Key 와 값이 저장된 Map, Entry를 저장한다. 이진 검색트리의 형태로 key-value 쌍으로 이루어진 데이터(Entry)를 저장하는데에 유용하다. HashMap 과 비교하자면, TreeMap 은 범위 검색 또는 정렬 사용에 더 유연하다. TreeMap 에 실행되는 자동 정렬은, 기본적으로 부모 키 값과 비교하여 키 값이 낮은 것은 왼쪽에, 키 값이 높은 것은 오른쪽에 Map.entry 를 저장한다. public static TreeMap map = new TreeMap(); static { map.put(1, "ABC"); map.put(2, "DEF"); } ... treeMap의 특정..

    Read more
  • Serializable interface Serializable.java public interface Serializable { } Person.java class Person implements Serializable { String name; String job; // transient String job; // transient : 이 멤버는 직렬화 대상에서 제외한다. (default 값 null 로 출력될거임) public Person() { } public Person(String name, String job) { this.name = name; this.job = job; } public String toString() { return name + "," + job; } } Serializ..

    Read more
  • interface Comparable 매개변수를 1개 받는다. package java.lang; import java.util.*; public interface Comparable { /* ... */ public int compareTo(T o); } Comparable 구현하기 1) 오름차순 public class Member implements Comparable { ... public int compareTo(Member member) { /** 오름차순 출력 */ if (this.memberId > member.memberId) { return 1; } else if (this.memberId < member.memberId) { return -1; } else { return 0; } } }..

    Read more
  • Todo. 가장 긴 문자열 추출하기 1. Stream 사용 public class ReduceTest { public static void main(String[] args) { String values[] = {"Hello", "World", "!"}; /* 가장 긴 length 문자열 추출 */ String reduce = Arrays.stream(values).reduce("", (s1, s2) -> { if (s1.getBytes().length >= s2.getBytes().length) { return s1; } else { return s2; } }); } } 2. Lamda 사용 class CompareString implements BinaryOperator { @Override publ..

    Read more
  • Function keyExtractor 선언 public class Test { private final Function keyExtractor; public Test(Function keyExtractor) { this.keyExtractor = keyExtractor; } ... } 호출 Test test = new Test(TestDto::getName) 람다식 전달 (TestDto::getName) 사용코드 public void testMethod(TestDto testDto) { /* 해당 item 으로 추출하겠다 */ String key = keyExtractor.apply(testDto); } name 을 key 값으로 추출될 것이다.

    Read more
  • 예제파일 DTO 1) Product.java package dto.Product; import lombok.Getter; import lombok.Setter; import java.util.Optional; public class Product { private int idx; private String productName; private int ordCnt; private int totalCnt; private Optional person; public int getIdx() { return idx; } public String getProductName() { return productName; } public int getOrdCnt() { return ordCnt; } public int ge..

    Read more
  • 참고 DTO package dto.Product; import java.util.Optional; public class Person { private int idx; private String personName; private Optional job; public int getIdx() { return idx; } public void setIdx(int idx) { this.idx = idx; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } public Optional getJob() { return job; ..

    Read more
  • forEach List numbers = Arrays.asList(2, 3, 5, 6); numbers.stream() .map(x -> x + 3) .filter(x -> x % 2 == 0) .limit(3) .forEach(System.out::println); /* 디버깅 x 결과 출력 */ 스트림의 파이프라인 연산을 디버깅하자. forEach 로 스트림 결과를 출력하거나 로깅할 수 있다. 하지만 forEach를 호출하게되면, 호출 순간에 전체 스트림이 소비된다. peek 스트림 연산 peek 을 활용하자. 호출 순간 전체 스트림을 소비하는 forEach 에 비해 peek은 실제로 스트림의 요소를 소비하지는 않는다. peek 은 자신이 확인한 요소를 파이프라인의 다음 연산으로 그대로 전달하고, 각..

    Read more
  • getOrDefault key 가 null 일 경우 default Value 를 설정할 수 있다. /* Map */ Map testMap2 = Map.ofEntries(entry("AAA", 10), entry("BBB", 20), entry("CCC", 30)); Key가 존재하면 해당 Value 를 그대로 출력한다. System.out.println(testMap2.getOrDefault("AAA", "NULL")); // 10 Key가 존재하지 않으면 설정된 "NULL"을 출력한다. System.out.println(testMap2.getOrDefault("DDD", "NULL")); // NULL 계산패턴 computeIfAbsent key 가 없을 경우 지정된 value를 쌍으로 Map 에 항목..

    Read more
  • forEach /* Map */ Map testMap2 = Map.ofEntries(entry("AAA", 10), entry("BBB", 20), entry("CCC", 30)); 전체 요소를 출력해보자. 기존 for문 for (Map.Entry entry : testMap2.entrySet()) { System.out.println(entry.getKey()); } java8 forEach testMap2.forEach((name, num) -> System.out.println(name + " : " + num)); sorted /* Map */ Map testMap2 = Map.ofEntries(entry("AAA", 10), entry("BBB", 20), entry("CCC", 30)); ke..

    Read more
  • List.of 오버로드 List 인터페이스의 of 메소드를 보면 아래와 같이 다양한 오버로드 버전이 있다. static List of() { return ImmutableCollections.emptyList(); } static List of(E e1) { return new ImmutableCollections.List12(e1); } static List of(E e1, E e2) { return new ImmutableCollections.List12(e1, e2); } static List of(E e1, E e2, E e3) { return new ImmutableCollections.ListN(e1, e2, e3); } ... static List of(E e1, E e2, E e3, E e..

    Read more
  • Copyright 2024. GRAVITY all rights reserved