Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

guava - Merging values contained by key in a map (Java)

final Multimap<String, Map.Entry<Integer, Integer>>[] actionMap = new Multimap[]{null};
final boolean[] loaded = {false};

db.execute(connection -> {
    PreparedStatement statement = null;
    ResultSet resultSet = null;

    actionMap[0] = ArrayListMultimap.create();
    try {
        statement = connection.prepareStatement("Blah Blah...
        while (resultSet.next()) {
            final String name = ...

            actionMap[0].put(name, new AbstractMap.SimpleEntry<>(int1, int2));

I have a map where I use SimpleEntry to insert two integer values (int1, int2). On a duplicate key I want to merge values of what's already mapped. My idea is computeIfPresent but I have no idea of the BiFunctions since I'm using AbstractMap.SimpleEntry to enter the two values. Any help would be much appreciated.

question from:https://stackoverflow.com/questions/65930821/merging-values-contained-by-key-in-a-map-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Before you put and overwrite, retrieve the existing value.

  • If you get null, there is no such value and you put as initially intended.
  • If you get something, merge your new data into something.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...