Post

Java) Map Iteration / List ImmutableCollections

Java) Map Iteration / List ImmutableCollections

This post was migrated from Tistory. You can find the original here.

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);
    }
}

Result
...\IdeaProjects\PreCamp
...\IdeaProjects\PreCamp
...\choi\IdeaProjects\PreCamp

Iterating over a 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());
        });
    }
}

If you declare the reference type as HashMap, the return type of t.entrySet() differs.

Initializing a 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});
        //Printing the List directly works fine.
        System.out.println(a);
        //List -> Array
        //Integer[] b = a.toArray(new Integer[a.size()]);

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

If you write List<Integer> a = Arrays.asList(new Integer[]{1,2,3,4});, IntelliJ
recommends List<Integer> a = List.of(new Integer[]{1,2,3,4}); instead, but
calling Collections.rotate on a List obtained from List.of throws an ImmutableCollections error.

A List obtained via asList doesn’t support add either.

If you actually need a mutable List going forward, just use Collections.addAll().

Collections

  • Use ArrayList for direct index access or when additions/removals are rare
  • Use LinkedList when there are many additions/removals
  • Use TreeSet when you need to search for values
This post is licensed under CC BY-NC 4.0 by the author.