Masterbp 05
Masterbp 05

Reputation: 11

Use triplets of integers vs HashMap<Integer,HashMap<Integer....>>

let's asume that there is a class Pos, implementing Lombok's equals and hashcode and have only immutable 3 integers (int x,y,z)

what may be more effective HashMap<Integer, HashMap<Integer, HashMap<Integer,T>>> or HashMap<Pos, T> ?

considering that i register values only at creation, and after that i only read values lots of times from the map, and also very often loop trough that map for every x and z possible for a specific y value (so in first case i even don't need to filter the y value, i just get the map for it, and filter null z maps for that y value)

Upvotes: 0

Views: 69

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338775

Records

Java 16+ offers a brief class definition now: records. So no need to resort to Lombok for that. See JEP 395: Records.

A record is appropriate when the main purpose of your class is to carry data transparently and immutably. The compiler implicitly creates the constructor, getters, equals and hashCode, and toString.

record Position ( int x , int y , int z ) {}

Collect your Position objects.

List< Position > positions = new ArrayList<>() ;
positions.add( new Person( 1 , 2 , 3 ) ) ;
…

From stream to map via Collectors.groupingBy

Group them by their y value.

Map< Integer, Set< Position > > positionsByY = 
    positions
    .stream()
    .collect(
        Collectors.groupingBy( Position :: y )
    );

When you want all x and z values for a particular valid of y, retrieve a list.

Upvotes: 1

Related Questions