在地图列表中查找键的值

发布于 2025-01-24 22:30:44 字数 1023 浏览 2 评论 0原文

我有 maps list< map< string,string>>的 list 输入

可以按以下方式表示:

[{AddressField=AddressUsageType, AddressValue=PRINCIPAL},
 {AddressField=StreetNumber, AddressValue=2020},
 {AddressField=StreetName, AddressValue=Some street}]

我想获得特定address> addressfieldaddressValue

例如,我想获得 value “ principal” key “ adverseUsageType”

我尝试使用过滤器和许多其他地图功能,但最终无法获得适当的解决方案。

这是我的代码片段,可获得第一键值对的值:

DataTable table;
List<Map<String,String>> input= table.asMaps(String.class, String.class);

    String AddressField = input.get(0).get("AddressField");
    String AddressValue = input.get(0).get("AddressValue");
    System.out.println("AddressField " +AddressField);
    System.out.println("AddressValue " +AddressValue);

这是上述片段的输出:

AddressField AddressUsageType
AddressValue PRINCIPAL

I have a list of maps List<Map<String,String>> input.

Which can be represented in the following manner:

[{AddressField=AddressUsageType, AddressValue=PRINCIPAL},
 {AddressField=StreetNumber, AddressValue=2020},
 {AddressField=StreetName, AddressValue=Some street}]

I would like to get the AddressValue for a particular AddressField.

For example, I want to get the value "PRINCIPAL" for the key "AddressUsageType".

I have tried using filters and many other MAP functions, but couldn't end up with a proper solution.

This is my code snippet that gets the value of 1st key-value pair:

DataTable table;
List<Map<String,String>> input= table.asMaps(String.class, String.class);

    String AddressField = input.get(0).get("AddressField");
    String AddressValue = input.get(0).get("AddressValue");
    System.out.println("AddressField " +AddressField);
    System.out.println("AddressValue " +AddressValue);

Here is the output of the above snippet:

AddressField AddressUsageType
AddressValue PRINCIPAL

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

少女净妖师 2025-01-31 22:30:45

由于在您的代码中,您有一个list,其中每个元素都是MAP带有单个映射,您可以流式传输列表,并过滤包含值的第一个映射地址useageType

您的代码可以像这样写:

Map<String, String> map = myList.stream()
        .filter(m -> m.values().contains("AddressUsageType"))
        .findFirst()
        .orElse(null);

if (map != null) {
    System.out.println("AddressField " + map.get("AddressField"));
    System.out.println("AddressValue " + map.get("AddressValue"));
}

这也是 onecompiler 的测试主。

Since in your code you have a List where each element is a Map with a single mapping, you could stream the list and filter for the first map containing the value AddressUsageType.

Your code could be written like this:

Map<String, String> map = myList.stream()
        .filter(m -> m.values().contains("AddressUsageType"))
        .findFirst()
        .orElse(null);

if (map != null) {
    System.out.println("AddressField " + map.get("AddressField"));
    System.out.println("AddressValue " + map.get("AddressValue"));
}

Here is also a test main at OneCompiler.

傲影 2025-01-31 22:30:45

我想从价值中获得地址值的价值
地址菲尔德。例如,

我想从键值“ processusageType”

获取value“ principal”

您正在滥用MAP此处。因为预计每张地图都有有限,定义明确的键,每个键在您的域中具有特殊的含义。每个地图都是指代表某种地址的意思。

强烈建议将这些数据在域模型中具有特定含义后立即将这些数据分组为自定义对象。

优点是:

  • 能够利用不同的数据类型作为值,而不是将它们存储为String
  • 您不必依靠字符串键。
  • 您可以获得干净的自我解释代码的优势(如果您使用清晰且精确的名称)。

我知道它可能是其他人很久以前开发的代码,或者您可能认为现在存储数据更容易。但是,您推迟重构的越多,它就越昂贵。

通过将对象视为集合,您可以使用深度嵌套的集合,例如地图的地图或将影响代码可维护性的地图列表的地图。

如果您选择将数据分组为域类,则可以处理此任务。

为了简单性和简洁性,我将使用Java 16记录。

public record UserAddress(AddressUsageType addressUsageType, int streetNumber, String streetName) {}

advellyUsageType将表示为enum。如果我正确理解的地址类型数量有限,那么以 enum 而不是依靠字符串值而存储此数据的数量有限,并且提供了额外的机会。

public enum AddressUsageType { PRINCIPAL, OTHER_TYPE }

这就是您可以通过能够从其类型中受益而不是将其视为字符串的每个userAddress对象从每个userAddress对象提取特定字段的

public static <T> List<T> getAddressValue(List<UserAddress> addresses,
                                          Function<UserAddress, T> keyExtractor) {
    return addresses.stream()
        .map(keyExtractor)
        .toList(); // available with Java 16 onwards
}

方式 : /em>地址和函数从地址对象提取特定属性。

main() - 演示

public static void main(String[] args) {
    List<UserAddress> addresses =
        List.of(new UserAddress(AddressUsageType.PRINCIPAL, 71, "greenStreet"),
                new UserAddress(AddressUsageType.PRINCIPAL, 83, "purpleStreet"),
                new UserAddress(AddressUsageType.OTHER_TYPE, 85, "pinkStreet"));
    
    List<AddressUsageType> addressUsageTypes = getAddressValue(addresses, UserAddress::addressUsageType);
    List<Integer> streetNumbers = getAddressValue(addresses, UserAddress::streetNumber);
    List<String> streetNames = getAddressValue(addresses, UserAddress::streetName);

    System.out.println("AddressUsageTypes:\n" + addressUsageTypes);
    System.out.println("StreetNumbers:\n" + streetNumbers);
    System.out.println("StreetNames:\n" + streetNames);
}

输出

AddressUsageTypes:
[PRINCIPAL, PRINCIPAL, OTHER_TYPE]
StreetNumbers:
[71, 83, 85]
StreetNames:
[greenStreet, purpleStreet, pinkStreet]

I would like to get the value of AddressValue from value of
AddressField. For eg.,

I want to get the value "PRINCIPAL" from the key value "AddressUsageType"

You are misusing the Map here. Because every map is expected to have a limited, well-defined set of keys, each of which has a particular meaning in your domain. And every map is mean to represent a some kind of address.

It's highly advisable to group these data into a custom object as soon as it has a particular meaning in your domain model.

The advantages are:

  • Ability to utilize different data types for values instead of storing them as String.
  • You don't have to rely on string keys.
  • You gain an advantage of clean self-explanatory code (in case if you would use clear and precise name).

I understand that it might the code that was developed long ago by someone else, or you might think that for now it's easier to store the data this was. But the more you're postponing the refactoring, the more expensive it becomes.

By treating the object as a collection, you might and up with deeply nested collections like map of maps or map of list of maps that will affect maintainability of code.

That how you can approach this task if you would choose to group the data into a domain class.

For sake of simplicity and conciseness, I would use Java 16 records.

public record UserAddress(AddressUsageType addressUsageType, int streetNumber, String streetName) {}

And AddressUsageType will be represented as enum. If I understood correctly there will a limited number of address type, so it's less error-prone to store this data as enum instead of relying on string values, and also gives few extra opportunities.

public enum AddressUsageType { PRINCIPAL, OTHER_TYPE }

And that's how you can extract a particular field from each UserAddress object in a list, by being able to benefit from its type instead of treating them as string:

public static <T> List<T> getAddressValue(List<UserAddress> addresses,
                                          Function<UserAddress, T> keyExtractor) {
    return addresses.stream()
        .map(keyExtractor)
        .toList(); // available with Java 16 onwards
}

The method shown above expects a list of addresses and a function which extracts a particular property from an addresses object.

main() - demo

public static void main(String[] args) {
    List<UserAddress> addresses =
        List.of(new UserAddress(AddressUsageType.PRINCIPAL, 71, "greenStreet"),
                new UserAddress(AddressUsageType.PRINCIPAL, 83, "purpleStreet"),
                new UserAddress(AddressUsageType.OTHER_TYPE, 85, "pinkStreet"));
    
    List<AddressUsageType> addressUsageTypes = getAddressValue(addresses, UserAddress::addressUsageType);
    List<Integer> streetNumbers = getAddressValue(addresses, UserAddress::streetNumber);
    List<String> streetNames = getAddressValue(addresses, UserAddress::streetName);

    System.out.println("AddressUsageTypes:\n" + addressUsageTypes);
    System.out.println("StreetNumbers:\n" + streetNumbers);
    System.out.println("StreetNames:\n" + streetNames);
}

Output

AddressUsageTypes:
[PRINCIPAL, PRINCIPAL, OTHER_TYPE]
StreetNumbers:
[71, 83, 85]
StreetNames:
[greenStreet, purpleStreet, pinkStreet]
陪你到最终 2025-01-31 22:30:44

您对地图的使用有些奇怪,因为您的实际键“ adverseUsageType”是地图内的一个值,每个地图只是一对键,值存储在静态键后面。如果您不能更改它,则可以使用类似的事情:

String key = "AddressUsageType";
String result = "";

for (Map<String,String> map : input)
{
    if (map.containsValue(key))
    {
        result = map.get("AddressValue");
        break;
    }
}

System.out.println(key + " is " + result);

Your usage of Maps is a bit odd here because your actual key "AddressUsageType" is a value inside the map and every map is just one pair of key and value stored behind static keys. If you can not change that, you could go with something like this:

String key = "AddressUsageType";
String result = "";

for (Map<String,String> map : input)
{
    if (map.containsValue(key))
    {
        result = map.get("AddressValue");
        break;
    }
}

System.out.println(key + " is " + result);
谈场末日恋爱 2025-01-31 22:30:44

过滤输入以仅保留包含addressField = addressUsageType的映射。然后使用.map函数提取addressValue输入,然后将它们收集到结果列表中。

public static void main(String[] args) {
    List<Map<String, String>> input = new ArrayList<>();
    Map<String, String> map = new HashMap<>();
    map.put("AddressField", "AddressUsageType");
    map.put("AddressValue", "PRINCIPAL");
    input.add(map);

    map = new HashMap<>();
    map.put("AddressField", "StreetNumber");
    map.put("AddressValue", "2020");
    input.add(map);
    map = new HashMap<>();
    map.put("AddressField", "StreetName");
    map.put("AddressValue", "Some street");
    input.add(map);

    map = new HashMap<>();
    map.put("AddressField", "AddressUsageType");
    map.put("AddressValue", "NOT_PRINCIPAL");
    input.add(map);
    
    List<String> collect = input.stream().filter(e -> e.get("AddressField").equals("AddressUsageType"))
            .map(e -> e.get("AddressValue")).collect(Collectors.toList());
    System.out.println(input);
    System.out.println(collect);
}

输出是

[{addressfield = addressusAgeType,addressValue = principal},{adversionField = streetnumber,adversyValue = 2020},{addressField = setwredname,adverthName,advermanValue =某些street},{addressfield = address field = adversionusAgeType,adverseValue = not_principal} not_principal}]

[principal,not_principal]

Filter the input to retain only maps which contain AddressField=AddressUsageType. Then extract the AddressValue entry using the .map function and gather them in a result list.

public static void main(String[] args) {
    List<Map<String, String>> input = new ArrayList<>();
    Map<String, String> map = new HashMap<>();
    map.put("AddressField", "AddressUsageType");
    map.put("AddressValue", "PRINCIPAL");
    input.add(map);

    map = new HashMap<>();
    map.put("AddressField", "StreetNumber");
    map.put("AddressValue", "2020");
    input.add(map);
    map = new HashMap<>();
    map.put("AddressField", "StreetName");
    map.put("AddressValue", "Some street");
    input.add(map);

    map = new HashMap<>();
    map.put("AddressField", "AddressUsageType");
    map.put("AddressValue", "NOT_PRINCIPAL");
    input.add(map);
    
    List<String> collect = input.stream().filter(e -> e.get("AddressField").equals("AddressUsageType"))
            .map(e -> e.get("AddressValue")).collect(Collectors.toList());
    System.out.println(input);
    System.out.println(collect);
}

The output is

[{AddressField=AddressUsageType, AddressValue=PRINCIPAL}, {AddressField=StreetNumber, AddressValue=2020}, {AddressField=StreetName, AddressValue=Some street}, {AddressField=AddressUsageType, AddressValue=NOT_PRINCIPAL}]

[PRINCIPAL, NOT_PRINCIPAL]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文