【问题标题】:how to get hashmap key and value from a string?如何从字符串中获取 hashmap 键和值?
【发布时间】:2018-10-29 10:28:12
【问题描述】:
HashMap<LocalDate, String>

我有一个包含字符串的 ListView(例如:“2014-05-10 示例”),我想用

删除选定的哈希图
hashmap.remove(LocalDate key, String value)

但我不确定如何从字符串中获取键和值

Context

我的对象来自一个名为“Inv”的类:

public class Inv {
    private String name;
    private String category;
    private LocalDate date;
    private Double price;
    private String info;
    private HashMap<LocalDate, String> mapMain;

上下文:“Inv”类中的对象是您购买的东西,例如汽车,哈希图包含对汽车进行的所有维护。

你能帮忙吗?

【问题讨论】:

  • hashmap.remove(LocalDate.parse(text.split(" ")[0]))
  • 字符串从何而来?在某个时候,您是否没有自己的日期,例如 LocalDate
  • 一根绳子有多长?
  • “一段字符串的长度是其长度的一半”:-)

标签: java listview javafx hashmap


【解决方案1】:

对于“如何从字符串中获取键和值”没有通用的解决方案。

这取决于你是否可以:

  • 明确地将字符串解析为键值信息,并
  • 从中重新创建一个关键对象。

请注意,您需要能够构造一个将equal 指向原始键的对象。如果你不能,那么问题就无法解决。

在您的情况下,如果我们可以假设日期字符串将始终采用该格式,那么@Andreas 的解决方案应该可以工作:

    hashmap.remove(LocalDate.parse(text.split(" ")[0]))

但这里有一个反例:

    HashMap<String, String>

和这样的条目:

    "key example string"
    "key 2 another example"

现在我们无法确定键的结束位置和值的开始位置。 (“2”部分是键还是值?“例子”呢?)

【讨论】:

    【解决方案2】:

    我的建议:不要使用包含键值对的ListView 来代替String 并使用自定义ListCells 来正确显示它们。

    示例:

    Map<LocalDate, String> data = ...
    ListView<Map.Entry<LocalDate, String>> listView = new ListView<>();
    listView.getItems().addAll(data.entrySet());
    listView.setCellFactory(l -> new ListCell<Map.Entry<LocalDate, String>>() {
    
        @Override
        protected void updateItem(Map.Entry<LocalDate, String> item, boolean empty) {
            super.updateItem(item, empty);
            setText((empty || item == null) ? "" : item.getKey() + " " + item.getValue());
        }
    
    });
    

    在这种情况下,您可以像这样删除选定的条目:

    int index = listView.getSelectionModel().getSelectedIndex();
    if (index >= 0) { // check, if selection exists
        Map.Entry<LocalDate, String> entry = listView.getItems().remove(index);
        // data.remove(entry.getKey(), entry.getValue());
        data.remove(entry.getKey());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-19
      • 2013-04-21
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-25
      相关资源
      最近更新 更多