使用Pair优雅的实现键值匹对

本文介绍了一种使用Java的Pair类来管理accessToken及其有效时间的方法,适用于需要定期更新accessToken的场景,尤其是在不使用Redis的情况下。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

场景:很多accessToken是有有效期的,在有效期后需要重新请求accessToken,此时我们需要把accessToken和有效时间关联起来,当然此时使用redis是最佳选择,但如果我们想放在java本地呢?java中常见键值对是map,但此时已经不适合了,因为accessToken和有效期都是变动的,而pair特别适合此场景。

/*
 * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package javafx.util;

import java.io.Serializable;
import javafx.beans.NamedArg;

 /**
  * <p>A convenience class to represent name-value pairs.</p>
  * @since JavaFX 2.0
  */
public class Pair<K,V> implements Serializable{

    /**
     * Key of this <code>Pair</code>.
     */
    private K key;

    /**
     * Gets the key for this pair.
     * @return key for this pair
     */
    public K getKey() { return key; }

    /**
     * Value of this this <code>Pair</code>.
     */
    private V value;

    /**
     * Gets the value for this pair.
     * @return value for this pair
     */
    public V getValue() { return value; }

    /**
     * Creates a new pair
     * @param key The key for this pair
     * @param value The value to use for this pair
     */
    public Pair(@NamedArg("key") K key, @NamedArg("value") V value) {
        this.key = key;
        this.value = value;
    }

    /**
     * <p><code>String</code> representation of this
     * <code>Pair</code>.</p>
     *
     * <p>The default name/value delimiter '=' is always used.</p>
     *
     *  @return <code>String</code> representation of this <code>Pair</code>
     */
    @Override
    public String toString() {
        return key + "=" + value;
    }

    /**
     * <p>Generate a hash code for this <code>Pair</code>.</p>
     *
     * <p>The hash code is calculated using both the name and
     * the value of the <code>Pair</code>.</p>
     *
     * @return hash code for this <code>Pair</code>
     */
    @Override
    public int hashCode() {
        // name's hashCode is multiplied by an arbitrary prime number (13)
        // in order to make sure there is a difference in the hashCode between
        // these two parameters:
        //  name: a  value: aa
        //  name: aa value: a
        return key.hashCode() * 13 + (value == null ? 0 : value.hashCode());
    }

     /**
      * <p>Test this <code>Pair</code> for equality with another
      * <code>Object</code>.</p>
      *
      * <p>If the <code>Object</code> to be tested is not a
      * <code>Pair</code> or is <code>null</code>, then this method
      * returns <code>false</code>.</p>
      *
      * <p>Two <code>Pair</code>s are considered equal if and only if
      * both the names and values are equal.</p>
      *
      * @param o the <code>Object</code> to test for
      * equality with this <code>Pair</code>
      * @return <code>true</code> if the given <code>Object</code> is
      * equal to this <code>Pair</code> else <code>false</code>
      */
     @Override
     public boolean equals(Object o) {
         if (this == o) return true;
         if (o instanceof Pair) {
             Pair pair = (Pair) o;
             if (key != null ? !key.equals(pair.key) : pair.key != null) return false;
             if (value != null ? !value.equals(pair.value) : pair.value != null) return false;
             return true;
         }
         return false;
     }
 }

pair保持一对键值对,使用getKey()和getValue()就能拿到,然后通过判断有效期进行更新key

### 键值对 `pair` 的概念 在编程中,键值对是一种常见的数据结构形式,用于存储由两部分组成的关联关系。这种结构通常被称为 `pair` 或者类似的名称,在不同的编程语言中有不同的实现方式。 #### C++ 中的 `std::pair` C++ 提供了标准模板库(STL)中的 `std::pair` 来表示键值对[^2]。它是一个简单的模板类,能够容纳两个不同类型的值。这两个值分别称为 **first** 和 **second**,可以通过成员变量 `.first` 和 `.second` 访问它们。 ```cpp #include <iostream> #include <utility> // std::pair, std::make_pair int main() { // 使用直接初始化的方式创建 pair 对象 std::pair<int, char> myPair1(10, 'A'); // 使用 make_pair 函数创建 pair 对象 std::pair<int, char> myPair2 = std::make_pair(20, 'B'); // 输出 first 和 second 值 std::cout << "myPair1: " << myPair1.first << ", " << myPair1.second << "\n"; std::cout << "myPair2: " << myPair2.first << ", " << myPair2.second << "\n"; return 0; } ``` 上述代码展示了如何通过两种方式创建 `std::pair` 类型的对象,并访问其内部的数据。 --- #### C# 中的 `KeyValuePair<TKey, TValue>` 在 C# 中,键值对的概念被封装到 `System.Collections.Generic` 名空间下的 `KeyValuePair<TKey, TValue>` 结构中[^1]。这个结构允许开发者显式地定义键和值的关系,并提供了只读的属性 `.Key` 和 `.Value` 来获取对应的值。 ```csharp using System; using System.Collections.Generic; class Program { static void Main() { var kvp = new KeyValuePair<string, int>("Apple", 5); Console.WriteLine($"Key: {kvp.Key}, Value: {kvp.Value}"); } } ``` 这段代码演示了如何实例化一个 `KeyValuePair<TKey, TValue>` 并打印它的键和值。 --- #### Boost.Hana 库中的键值对 Boost.Hana 是一个现代 C++ 库,支持泛型编程和元编程。在其框架下,键值对可以通过 `boost::hana::make_pair` 构造函数生成[^3]。这种方式特别适合于处理复杂的编译期计算场景。 ```cpp #include <boost/hana.hpp> namespace hana = boost::hana; struct name_key {}; struct age_key {}; int main() { auto person = hana::make_tuple( hana::make_pair(name_key{}, "Alice"), hana::make_pair(age_key{}, 30) ); hana::unpack(person, [](auto&& name, auto&& age) { std::cout << "Name: " << name << ", Age: " << age << '\n'; }); return 0; } ``` 此示例说明了如何利用 Hana 创建带标签的键值对,并将其解包为实际使用的对象。 --- #### 排序操作中的应用 当涉及到基于键值对的排序时,C++ 提供了一种灵活的方式来完成这一需求。例如,可以将 `std::map` 转换为 `std::vector<std::pair<T, U>>` 后进行自定义排序[^4]。 ```cpp #include <iostream> #include <vector> #include <map> #include <algorithm> bool cmp(const std::pair<std::string, int>& a, const std::pair<std::string, int>& b) { return a.second > b.second; // 按照 value 进行降序排列 } int main() { std::map<std::string, int> mp = {{"apple", 10}, {"banana", 20}, {"cherry", 15}}; std::vector<std::pair<std::string, int>> vec(mp.begin(), mp.end()); std::sort(vec.begin(), vec.end(), cmp); for (const auto& p : vec) { std::cout << p.first << ": " << p.second << "\n"; } return 0; } ``` 以上代码片段实现了按照 `pair` 的第二个元素(即值)进行排序的功能。 --- ### 总结 键值对作为一种基础的数据结构,广泛应用于多种编程语言中。无论是 C++ 的 `std::pair`、C# 的 `KeyValuePair<TKey, TValue>`,还是 Boost.Hana 的高级抽象工具,都体现了键值对的强大功能及其灵活性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值