双方向不変辞書

immutableなMapを二つ使って双方向に辞書引きできるようにする。

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static java.util.Map.entry;

public class BidirectionalMapTest {
    public static void main(String[] args) {
        Map<Integer, String> map = Map.ofEntries(
            entry(0, "nop"),
            entry(21, "iload"),
            entry(54, "istore"),
            entry(87, "pop"),
            entry(96, "iadd"),
            entry(133, "i2l"),
            entry(148, "lcmp"),
            entry(167, "goto"),
            entry(178, "getstatic"),
            entry(196, "wide"),
            entry(202, "breakpoint")
        );
        @SuppressWarnings("unchecked")
        Map<String, Integer> pam = Map.ofEntries(
            map.entrySet().stream()
                .map(e -> entry(e.getValue(), e.getKey()))
                .toArray(Map.Entry[]::new)
        );
        System.out.println(map);
        System.out.println(pam);

        List<Integer> opcodes1 = List.of(87, 96, 0, 196);
        List<String> mnemonics = opcodes1.stream().map(map::get).collect(Collectors.toList());
        List<Integer> opcodes2 = mnemonics.stream().map(pam::get).collect(Collectors.toList());
        System.out.println(opcodes1);
        System.out.println(mnemonics);
        System.out.println(opcodes2);
    }
}

癪だけどアノテーションSuppressWarningsがないことには無検査警告が煩い。
Map#ofMap#ofEntriesの系統で、この他に、
IterableとかCollectionとか
Iteratorとかを引数に取るメソッドがあればいいのだが。

$ java BidirectionalMapTest
{54=istore, 196=wide, 0=nop, 133=i2l, 178=getstatic, 96=iadd, 87=pop, 167=goto, 21=iload, 202=breakpoint, 148=lcmp}
{i2l=133, breakpoint=202, lcmp=148, nop=0, pop=87, istore=54, iadd=96, iload=21, goto=167, getstatic=178, wide=196}
[87, 96, 0, 196]
[pop, iadd, nop, wide]
[87, 96, 0, 196]