자바) Map반복/ List ImmutableCollections
자바) Map반복/ List ImmutableCollections
이 글은 Tistory에서 이전된 포스팅입니다. 원본은 여기에서 확인할 수 있습니다.
pwd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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반복
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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초기화
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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
이 기사는 저작권자의 CC BY-NC 4.0 라이센스를 따릅니다.