Gumilar
Gumilar

Reputation: 105

Java Get last key from Hashmap

previously I apologized if my question is classic. but because I just learned Java programming for android, I didn't really understand the commands.

I'm currently making an application with the code section as follows:

Map<Integer, CompTypes> mapCompTypes = new java.util.HashMap();

class CompTypes
{
    int androidId;
    AndroidViewComponent component;
    String text;
    String type;
    CompTypes(int androidId, AndroidViewComponent component, String type, String text)
    {
        this.androidId = androidId;
        this.component = component;
        this.type = type;
        this.text = text;
    }
}

public void SendMessage(HVArrangement container, String message, String dateTime, int fontSize, int fontColor, int alignment, int startid)
{
    int id = Integer.parseInt(ChatBox.this.GetLastId());
    TextBox comp = new TextBox(vertical);
    comp.getView().setId(id);
    comp.Text(message);
    comp.FontSize(fontSize);
    comp.TextColor(fontColor);
    comp.MultiLine(true);
    comp.Enabled(false);
    comp.RequestFocus();
    mapCompTypes.put(Integer.valueOf(id), new CompTypes(id, comp, compType, comp.Text()));

    int id2 = id + 1;
    Label dt = new Label(vertical);
    dt.getView().setId(id2);        
    ((TextView)dt.getView()).setText(android.text.Html.fromHtml(datetime));
    dt.HTMLFormat(true);
    dt.Text(datetime);
    dt.getView().setOnClickListener(this);
    dt.getView().setOnLongClickListener(this);
    mapCompTypes.put(Integer.valueOf(id2), new CompTypes(id2, dt, compType, dt.Text()));
}


public String GetLastId()
{
    // how to get last id?
    //return ids;
}

at the moment I'm having trouble getting the value from id as the last id from Hashmap. I've read a number of questions and answers here that "Maps don't have the last entry, it's not part of their contract." is there another way to get the last id?

Upvotes: 1

Views: 17908

Answers (4)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

I can see that you increase id as key for the map. So to get your last id you have two options:

  • Use LinkedHashMap, then get all keys and get the last one
  • Use TreeMap with reverse order comparator, then get the first key (this one will be with highes value, i.e. the last).

Map<Integer, CompTypes> mapCompTypes = new TreeMap<>(Comparator.reverseOrder());

final class CompTypes {
    private final int androidId;
    private final AndroidViewComponent component;
    private final String text;
    private final String type;

    CompTypes(AndroidViewComponent component, String type)  {
        this.androidId = component.getView().getId();
        this.component = component;
        this.type = type;
        this.text = component.Text();
    }
}

public void SendMessage(HVArrangement container, String message, String datetime, int fontSize, int fontColor, int alignment, int startid) {
    int id = Integer.parseInt(ChatBox.this.GetLastId());
    mapCompTypes.put(id, new CompTypes(createCompTypes(createTextBox(id, message, fontSize, fontColor)), compType));
    mapCompTypes.put(id + 1, new CompTypes(createLabel(id, datetime)));
}

private CompTypes createCompTypes(AndroidViewComponent component) {
    return new CompTypes(component, compType)
}

private TextBox createTextBox(int id, String message, int fontSize, int fontColor) {
    TextBox textBox = new TextBox(vertical);
    textBox.getView().setId(id);
    textBox.Text(message);
    textBox.FontSize(fontSize);
    textBox.TextColor(fontColor);
    textBox.MultiLine(true);
    textBox.Enabled(false);
    textBox.RequestFocus();
    return textBox;
}

private Label createLabel(int id, String datetime) {
    Label label = new Label(vertical);
    label.getView().setId(id);        
    ((TextView)dt.getView()).setText(android.text.Html.fromHtml(datetime));
    label.HTMLFormat(true);
    label.Text(datetime);
    label.getView().setOnClickListener(this);
    label.getView().setOnLongClickListener(this);
    return label;
}

public String GetLastId() {
    int lastId = mapCompTypes.isEmpty() ? -1 : mapCompTypes.keySet().iterator().next();
    //return ids;
}

Upvotes: 1

Amit
Amit

Reputation: 235

HashMap doesn't maintain ordering. If you want to maintain insertion ordering then use LinkedHashMap. It can be used like this.

 private static String getLastId() {
        Map<Integer, String> map = new LinkedHashMap<>();
        map.put(1, "A");
        map.put(2, "B");
        map.put(3, "C");
        String lastObject = "";
        for (Map.Entry<Integer, String> entry : map.entrySet()) {
            lastObject = entry.getValue();
        }
        return lastObject;
    }

If you have map key as natural ordering. Then you can use TreeMap or pass a comparator to TreeMap. Here is an snippet to do that.

private static String getLastId() {
    Map<Integer, String> map = new TreeMap<Integer,String>();
    map.put(1, "A");
    map.put(2, "B");
    map.put(3, "C");
    return ((TreeMap<Integer, String>) map).lastEntry().getValue();
}

See documentation here of LinkedHashMap and TreeMap.

Upvotes: 3

Zaid Mirza
Zaid Mirza

Reputation: 3709

HaspMap doesn't preserve order.So,Its not possible to get any element via position either last, first or middle.

One thing you can do is that save your key in some variable when do insertion in HashMap and access that variable to get key of your last object. For guarantee order you can also looked for LinkedHashMap

Upvotes: 6

Irshaad Moosuddee
Irshaad Moosuddee

Reputation: 240

I would suggest you to use a TreeMap instead where you can make use of lastEntry() method.

Map<Integer, CompTypes> mapCompTypes = new TreeMap();
mapCompTypes.lastEntry()

Upvotes: 0

Related Questions