java Map반복/ List ImmutableCollections

cornpip·2023년 5월 10일
0

자바

목록 보기
12/19
post-thumbnail

23.5.2 ~ 23.5.19 사전 캠프 기간의 TIL 기록입니다!
TIL: Today I Learned

pwd

public class Main {
    public static void main(String[] args) {
        String currentPath = Paths.get("").toAbsolutePath().toString();
        String currentPath2 = new File("").getAbsolutePath();
        System.out.println(System.getProperty("user.dir"));
        System.out.println(currentPath);
        System.out.println(currentPath2);
    }
}

결과
...\IdeaProjects\PreCamp
...\IdeaProjects\PreCamp
...\choi\IdeaProjects\PreCamp

Map반복

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> t = new HashMap();
        t.put("a", 100); t.put("b", 200);
        
        // entrySet()
        for(Map.Entry<String, Integer> entry:t.entrySet()){
            System.out.printf("%s : %d\n", entry.getKey(), entry.getValue());
        }

		// iterator()
        Iterator it = t.entrySet().iterator();
        while(it.hasNext()){
            Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) it.next();
            System.out.printf("%s : %d\n", entry.getKey(), entry.getValue());
        }
		
        // lambda
        t.forEach((k, v) -> {
            System.out.printf("%s : %d\n", k, v);
        });

		// stream
        t.entrySet().stream().forEach(entry->{
            System.out.printf("%s : %d\n", entry.getKey(), entry.getValue());
        });
    }
}

참조타입 HashMap으로 선언할 경우 t.entrySet()의 반환 타입이 다르다.

List초기화

public class Main {
    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>();
        Collections.addAll(a, new Integer[]{1,2,3,4});
        //List는 그냥 출력 나옴.
        System.out.println(a);
        //List -> Array
        //Integer[] b = a.toArray(new Integer[a.size()]);

        Collections.rotate(a, 2);
        System.out.println(a);
    }
}
결과
[1, 2, 3, 4]
[3, 4, 1, 2]

List<Integer> a = Arrays.asList(new Integer[]{1,2,3,4});를 쓰면 idle이
List<Integer> a = List.of(new Integer[]{1,2,3,4});를 추천하는데
List.of 로 얻은 List에 Collections.rotate를 하면 ImmutableCollections blabla 하는 에러가 출력된다.

asList 로 얻은 List는 add 안된다.

그냥 계속 사용하려는 변환이면 collections.addAll() 쓰자.

Collection

  • 인덱스 바로 접근하거나 추가 삭제 적으면 ArrayList
  • 추가 삭제가 많으면 LinkedList
  • 값을 검색하려면 TreeSet
profile
https://cornpip.tistory.com 티스토리로 이전했습니다!

0개의 댓글