alorithm

JAVA 문법 모음집

Hannana. 2025. 3. 22. 08:53
728x90
반응형
  • 배열 중복제거하기(+정렬위한 HashSet사용) 
    • 방법: 배열을 HashSet에 담고 다시 배열로 담기
    • 구현: 
HashSet<Integer> set = Arrays.stream(nums).boxed().collect(Collections.toSet());
int[] newArr = set.stream().mapToInt(Integer::intValue).toArray(); //HashSet을 배열에 다시 담기

배열의 요소를 stream으로 돌기 위해 Arrays.stream(arr).boxed() 사용, + collect로 다른 자료형으로 모으기

 

 

  • 리스트 중복 제거하기(+저장되는 순서 유지 위한 LinkedHashSet사용)
    • 방법: 리스트를 LinkedHashSet에 담고 다시 리스트로 담기
    • 구현:
Set<Integer> toSet = new LinkedHashSet<>(list);
List<Integer> newList = new ArrayList<>(toSet); //HashSet을 리스트에 다시 담기

 

 

  • 배열 -> 리스트
    • 구현:
Arrays.asList(arr);

 

 

 

  • 특정 문자 있는지 여부 판단하기
    • 방법: String "" 과 indexOf로 판별
    • 구현:
if("aeiou".indexOf(x)>=0)

 0이상이면 aeiou 중에 x가 있는 것임(for)

 

 

 

  • 리스트 요소 람다식으로 체크하기
    • 구현:
if(list.stream().anyMatch(x-> x>3)){
	que.add(x);
}

 

-배열과 달리 리스트는 직접 .stream() 가능+인자없음, anyMatch(x -> ...) 로 리스트 요소 조건 체크 가능

-리턴값은 true/false 로 if와 함께 쓴다.

반응형