Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of Map vs Optional in Java [duplicate]

Tags:

java

I have a doubt about the performance difference between these two things, get an object directly from a hashmap with the key vs get it from an Optional from an ArrayList. I will use these to save big amounts of data.

Note: the example below is only to show what I mean; I don't use static except in utils or specific things, I say this to prevent comments about static.

public class Main {

    private static final List<User> users = Arrays.asList(new User(UUID.randomUUID()), new User(UUID.randomUUID()), new User(UUID.randomUUID()));

    public static Optional<User> getUserByUUID(final UUID uuid){
        return users.stream().filter(user -> user.getUuid().equals(uuid)).findFirst();
    }

    @RequiredArgsConstructor
    @Getter@Setter
    private static class User{
        private final UUID uuid;
        private int points;
        private int gems;
    }

}

vs

public class Main {

    private static final Map<UUID, User> users = new HashMap<UUID, User>(){{
        put(UUID.randomUUID(), new User());
        put(UUID.randomUUID(), new User());
    }};
            

    public static User getUserByUUID(final UUID uuid){
        if(users.containsKey(uuid))
            return users.get(uuid);
        return null;
    }

    @RequiredArgsConstructor
    @Getter@Setter
    private static class User{
        private int points;
        private int gems;
    }

}

My point is, if one is better than the another one in terms of performance, is it insignificant?

like image 748
R3bck Avatar asked Mar 17 '26 19:03

R3bck


1 Answers

Map#get will always be more performant than creating a Stream from a List and looking for a specific entry.

Map#get will give you a time complexity of O(1) basically

List#stream instead will give you a time complexity of O(n) plus extra space complexity: creation of a Stream and creation of an Optional


That said, if you have big amounts of data loaded in memory, this might lead to performance problems / OutOfMemoryErrors

It would be interesting to dig further in the problem and see if there isn't another way to handle this specific problem without loading big amounts of data directly in memory of the JVM

like image 171
Yassin Hajaj Avatar answered Mar 19 '26 09:03

Yassin Hajaj