문제

I am new to Java. I have a requirement of holding a lookup table in memory(Abbreviations and their expansions). I was thinking of using Java Hash map. But I want to know if that really is the best approach. Also, If there are any equivalent libraries in Google Guava, for the same requirement. I want it to me optimized and very efficient w.r.t time and memory

도움이 되었습니까?

해결책

Using Maps

Maps are indeed fine for this, as used below.

Apparently, it's a bit early for you to care that much about performance or memory consumption though, and we can't really help you if we don't have more context on the actual use case.

In Pure Java

final Map<String, String> lookup = new HashMap<>();

lookup.put("IANAL", "I Ain't A Lawyer");
lookup.put("IMHO", "In My Humble Opinion");

Note that there are several implementations of the Map interface, or that you can write your own.

Using Google Guava

If you want an immutable map:

final Map<String, String> lookup = ImmutableMap.<String, String>builder()
    .put("IANAL", "I Ain't A Lawyer")
    .put("IMHO", "In My Humble Opinion")
    .build();

Retrieving Data

Then to use it to lookup an abbreviation:

// retrieval:
if (lookup.containsKey("IMHO")) {
  final String value = lookup.get("IMHO");

  /* do stuff */
}

Using Enums

I was speaking of alternatives...

If you know at coding time what the key/value pairs will be, you may very well be better off using a Java enum:

class Abbrevations {
  IANAL  ("I Ain't A Lawyer")
  IMHO   ("In My Humble Opinion");

  private final String value;

  private Abbreviations(final String value) {
    this.value = value;
  }

  public String getValue() {
    return (value);
  }

}

You can then lookup values directly, ie either by doing this:

Abbreviations.IMHO.getValue()

Or by using:

Abbreviations.valueOf("IMHO).getValue()

Considering where you seem to be in your learning process, I'd recommend you follow the links and read through the Java tutorial and implement the examples.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top