728x90 언어/JAVA18 int[] to Integer[] int[] intArray IntStream.of(intArray).boxed().toArray(Integer[]::new); 2023. 1. 2. Ubuntu Java 11 설치 (Open JDK) https://codechacha.com/ko/ubuntu-install-open-jdk11/ Ubuntu 20.04 - OpenJDK 11 설치, 삭제 Ubuntu 20.04에 OpenJdk 11을 설치하는 방법을 소개합니다. apt 명령어로 쉽게 설치할 수 있습니다. 만약 apt로 설치할 수 없다면 설치 파일을 다운로드하여 직접 설치하는 방법이 있습니다. 두가지 방법 codechacha.com 2022. 4. 10. 람다를 활용한 비교 기본 Lambda 사용방법 lambda 표현식을 이용하면 익명클래스를 간단하게 변경할 수 있습니다. 위의 예제를 한번 바꿔 보겠습니다. public void sortEntitiesByName() { List humans = Arrays.asList(new Human("A", 20), new Human("B", 21)); Collections.sort(humans, (Human h1, Human h2) -> h1.getName().compareTo(h2.getName())); assertThat(humans.get(0).getAge(), is(21)); } 간단하게 lambda 표현식을 적용했을 때 이렇게 간단해지는 것을 확인할 수 있습니다. lambda 표현식을 적용할 경우 type에 대해 명시하지 않아.. 2021. 10. 15. 자바에서 HashMap을 위한 커스텀 키 생성 방법 Java에서 HashMap을 위한 Custom Key 정의하기 Java의 HashMap 자료구조는 고유한 값인 Key와 1:1로 연관되는 값(Value)을 하나의 쌍(Pair)로 하여 여러 개의 쌍을 저장하는 자료구조입니다. 흔히 Key 값으로 문자열이나 정수값을 사용하는 것으로도 충분합니다. 그러나 기능에 따라서 개발자가 특별한 Key에 대한 타입을 정의해야할 필요가 있습니다. 만약 개발자가 Key 타입으로 아래와 같은 클래스를 정의했다고 합시다. public class Identifier { private long A; private long B; private long C; public Identifier(long A, long B, long C) { this.A = A; this.B = B; th.. 2021. 10. 1. 자바 컬렉션 배열 사용하기 new 로 배열 크기 할당할때 제네릭 사용하지 않고 바로 [] 사용 ArrayList[] list = new ArrayList[V+1]; for (int i = 1; i < V+1; i++) { list[i] = new ArrayList(); } 2021. 8. 25. PrioryityQueue(우선순위 큐) Priority Queue의 특징 1. 높은 우선순위의 요소를 먼저 꺼내서 처리하는 구조 (큐에 들어가는 원소는 비교가 가능한 기준이 있어야함) 2. 내부 요소는 힙으로 구성되어 이진트리 구조로 이루어져 있음 3. 내부구조가 힙으로 구성되어 있기에 시간 복잡도는 O(NLogN) 4. 응급실과 같이 우선순위를 중요시해야 하는 상황에서 쓰임 Priority Queue 사용법 Priority Queue 선언 import java.util.PriorityQueue; //import //int형 priorityQueue 선언 (우선순위가 낮은 숫자 순) PriorityQueue priorityQueue = new PriorityQueue(); //int형 priorityQueue 선언 (우선순위가 높은 숫자 순).. 2021. 8. 24. 다음 순열(Next Permutation)을 활용한 조합 생성 public class CombNextPermutationTest { public static void main(String[] args) { int[] input = {7,1,4,2,3}; int N = input.length; int R = 4; int[] p = new int[N]; // 뒤쪽부터 R개만큼 1채우기 int cnt = 0; while(++cnt=numbers[i]) { --i; } if(i==0) return false; // setp2 i-1 위치값과 교환할 큰 값 찾기 int j = N-1; while(numbers[i-1]>=numbers[j]) { --j; } // step3 i-1 위치값과 j 위치값 교환 swap(numbers,i-1,j); // step4 꼭대기부터 맨 뒤.. 2021. 8. 12. 다음 순열 (Next Permutation) package day11; import java.util.Arrays; public class NextPermutationTest { public static void main(String[] args) { int[] input = {7,1,4}; Arrays.sort(input); do { System.out.println(Arrays.toString(input)); }while(np(input)); } // 다음 큰 순열이 있으면 true, 없으면 false private static boolean np(int[] numbers) { int N = numbers.length; // step1 꼭대기(i)를 찾는다. 꼭대기를 통해 교환 위치(i-1) 찾기 int i=N-1; while(i>0 && nu.. 2021. 8. 12. 2차원 배열 회전 (시계 , 반 시계) // 시계 방향 static int[][] oper3(int[][] arr,int row, int col) { int[][] arr2 = new int[col][row]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { arr2[j][row-i-1] = arr[i][j]; } } return arr2; } // 반시계 static int[][] oper4(int[][] arr,int row, int col) { int[][] arr2 = new int[col][row]; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { arr2[col-j-1][i] = arr[i][j]; }.. 2021. 8. 12. 링크드 리스트 구현 public class SingleLinkedList { private Node head; public void addFirstNode(String data) { Node newNode = new Node(data,head); head = newNode; } public Node getLastNode() { for(Node currNode=head;currNode!=null;currNode=currNode.link) { if(currNode.link==null) { return currNode; } } return null; } public void addLastNode(String data) { if(head==null) { addFirstNode(data); return; } Node lastNode.. 2021. 8. 9. 자바 문자열 뒤집기 백준 1259 팰린드롬 체크 StringBuilder reverseStr= new StringBuilder(str); if(reverseStr.reverse().toString().equals(str)) { System.out.println("yes"); } else System.out.println("no"); 2021. 8. 6. 자바 문자열 뒤집기 백준 1259 팰린드롬 체크 StringBuilder reverseStr= new StringBuilder(str); if(reverseStr.reverse().toString().equals(str)) { System.out.println("yes"); } else System.out.println("no"); 2021. 8. 6. 자바 sort (Compareable, Comparator, lambda) 백준 1181 단어 정렬 우리가 해야할 것은 단어 정렬이니 기본적으로 정렬할 배열의 타입은 String 이 될 것이다. 즉 T 는 String 이 된다는 것이다. 이렇게 Comparator 의 타입을 넣었으면, 다음으로 해야할 것은 compare 메소드를 오버라이딩하는 것이다. 즉, 아래 코드가 기본형이 되겠다. String[] arr = new String[N];// 배열에 단어가 이미 초기화 되었다고 가정 Arrays.sort(arr, new Comparator() { @Override public int compare(String s1, String s2) { /* 정렬방법 구현 */ } }); 기본적으로 양수일경우 Arrays.sort()에서 정렬 알고리즘에 의해 위치를 바꾸고, 0 이나 음의 정.. 2021. 8. 6. 자바 조합 생성 import java.util.Arrays; public class Comb { static int N=5,R=2; static int[] input= {1,5,7,8,9}; static int[] numbers=new int[R]; public static void main(String[] args) { comb(0,0); } public static void comb(int cnt, int start) { if(cnt==R) { System.out.println(Arrays.toString(numbers)); return; } for(int i = start;i 2021. 8. 3. java 순열, 중복 순열, 조합, 중복 조합 import java.util.Arrays; import java.util.Scanner; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.XsiNilLoader.Array; public class DiceTest { static int N,numbers[],totalCnt; static boolean[] isSelected; public static void main(String[] args) { Scanner sc = new Scanner(System.in); N= sc.nextInt(); int M=sc.nextInt(); numbers = new int[N]; totalCnt = 0; switch(M) { case 1 : // 중복순열 dice.. 2021. 8. 3. StringBuilder 1. 문자열의 조작을 지원하는 클래스 2. 자바에서 상수로 취급되는 문자열을 자작 시마다 새로운 문자열이 생성되는 것을 방지해줌 public class StringBuilderTest { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); String test=sb.append("String ").append("!!").toString(); System.out.println(test); sb.setLength(sb.length()-2); System.out.println(sb); } } 2021. 8. 2. BufferedReader public class BufferedReaderTest { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); char [] ch = in.readLine().toCharArray(); for(char c :ch) { System.out.println(c); } StringTokenizer st = new StringTokenizer(in.readLine()," "); int i = Integer.parseInt(st.nextToken()); int j = Integer.parseInt(st.nextToken()); .. 2021. 8. 2. java input.txt 읽기 코테 하다보면 input.txt로 쉽게 읽기 import java.util.Scanner; import java.io.FileInputStream; class Solution { public static void main(String args[]) throws Exception { String inputTxt = Solution.class.getResource(".").getPath()+"input.txt"; System.setIn(new FileInputStream(inputTxt)); Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for (int test_case = 1; test_case 2021. 7. 29. 이전 1 다음 728x90