是否有一种整洁的方式将列表转换为地图,将键设置为原始集合的元素,并设置为Java中的枚举的元素

发布于 2025-01-27 06:15:21 字数 900 浏览 3 评论 0原文

Java Newbie ... 我有一个类似的字典:

electronictypeModelsMap =
{
"laptops" => ["macbook", "thinkpad", "yoga"],
"desktops" => ["macmini", "imac", "otherDesktop"],
"smartphones" => ["iphone", "galaxy5", "oneplus"]
}

只有上面的3个键只有少数键,但是每个值中会有几百个元素(列表)

。周围: dictionary.get(“ MacBook”)会返回“笔记本电脑”,

因此我想我想将每个列表的每个元素作为一个键,将相应值设置为原始密钥,将每个列表的每个元素作为键。 像这样:

{
"macbook" => "laptops", 
"thinkpad" => "laptops", 
"yoga"=> "laptops", 
"macmini" => "desktops", 
"imac" => "desktops", 
"otherDesktop" => "desktops",
"iphone" => "smartphones", 
"galaxy5" =>  "smartphones", 
"oneplus" => "smartphones", 
}

在Java 11中是否有一种整洁的方式?

在红宝石中,你可以做这样的事情

newMap = Hash.new 
electronictypeModelsMap.each do |k,v|
    v.each do |value| 
        newMap[value] = k 
    end 
end 

Java newbie...
I have a dictionary like so:

electronictypeModelsMap =
{
"laptops" => ["macbook", "thinkpad", "yoga"],
"desktops" => ["macmini", "imac", "otherDesktop"],
"smartphones" => ["iphone", "galaxy5", "oneplus"]
}

There will only ever be a small number of keys like the 3 above but there will be a few hundred elements in each value (list)....

I want to be able to query it the other way around so :
dictionary.get("macbook") would return "laptops"

So I guess I want to convert into a new map with each element of each list as a key with the corresponding value set to the original key.
like this:

{
"macbook" => "laptops", 
"thinkpad" => "laptops", 
"yoga"=> "laptops", 
"macmini" => "desktops", 
"imac" => "desktops", 
"otherDesktop" => "desktops",
"iphone" => "smartphones", 
"galaxy5" =>  "smartphones", 
"oneplus" => "smartphones", 
}

Is there a neat way of doing this in Java 11?

In ruby you could do something like this

newMap = Hash.new 
electronictypeModelsMap.each do |k,v|
    v.each do |value| 
        newMap[value] = k 
    end 
end 

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

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

发布评论

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

评论(3

最偏执的依靠 2025-02-03 06:15:21

假设您的地图如下:

Map<String,List<String>> electronictypeModelsMap = 
     Map.of("laptops",     List.of("macbook", "thinkpad", "yoga"),
            "desktops",    List.of("macmini", "imac", "otherDesktop"),
            "smartphones", List.of("iphone", "galaxy5", "oneplus"));

最简单的解决方案可能是使用嵌套foreach

Map<String,String> reMapped = new HashMap<>();

electronictypeModelsMap.forEach((key,list) -> {
    list.forEach(item -> {
        reMapped.put(item, key);
    });
});

Assuming you have a map like below:

Map<String,List<String>> electronictypeModelsMap = 
     Map.of("laptops",     List.of("macbook", "thinkpad", "yoga"),
            "desktops",    List.of("macmini", "imac", "otherDesktop"),
            "smartphones", List.of("iphone", "galaxy5", "oneplus"));

the simplest solution could be to use a nested forEach

Map<String,String> reMapped = new HashMap<>();

electronictypeModelsMap.forEach((key,list) -> {
    list.forEach(item -> {
        reMapped.put(item, key);
    });
});
守不住的情 2025-02-03 06:15:21

如果您确定每个值列表中的每个元素都将为 unique (即在所有 map 的范围中不同),则可以采用以下方法:

  • 创建一个流在入口集上;
  • 使用flatmap()通过根据列表的每个元素以及当前列表的映射键创建 new entry 来弄平条目,从而使值变成一个值钥匙,反之亦然。
  • 使用collectors.tomap()将数据收集到地图中。
Map<String, List<String>> source = 
    Map.of("laptops", List.of("macbook", "thinkpad", "yoga"),
           "desktops", List.of("macmini", "imac", "otherDesktop"),
           "smartphones", List.of("iphone", "galaxy5", "oneplus"));

Map<String, String> result = 
    source.entrySet().stream()
        .flatMap(entry -> entry.getValue().stream().map(element -> 
                          Map.entry(element, entry.getKey())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

result.forEach((k, v) -> System.out.println(k + "  =>  " + v));

output

galaxy5  =>  smartphones
macmini  =>  desktops
macbook  =>  laptops
etc.

注意 ,如果在初始映射中将至少具有一个元素(例如“ MacBook”),该元素已映射到多个类别,上面列出的 collector 将无法解析重复项,并且会导致IllegalstateException。作为一种补救措施,您需要定义如何通过提供MergeFunction作为tomap()的第三个参数来覆盖值,或者使用collector collector collector.groupingbybybybybybybybybybybybybybybybybyby ()而不是保留映射到同一键的所有值。

If you're certain that every element in each list of values will be unique (i.e. distinct in the scope of all map) you can take the following approach:

  • Create a stream over the entry set;
  • Flatten the entries using flatMap() by creating a new entry based on each element of the list and a key to which the current list was mapped, so that a value becomes a key and vice versa.
  • Collect the data into a map using Collectors.toMap().
Map<String, List<String>> source = 
    Map.of("laptops", List.of("macbook", "thinkpad", "yoga"),
           "desktops", List.of("macmini", "imac", "otherDesktop"),
           "smartphones", List.of("iphone", "galaxy5", "oneplus"));

Map<String, String> result = 
    source.entrySet().stream()
        .flatMap(entry -> entry.getValue().stream().map(element -> 
                          Map.entry(element, entry.getKey())))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

result.forEach((k, v) -> System.out.println(k + "  =>  " + v));

Output

galaxy5  =>  smartphones
macmini  =>  desktops
macbook  =>  laptops
etc.

Note that if in the initial map will have at least one element (like "macbook") that has been mapped to more than one category, the collector listed above will be unable to resolve duplicates, and it'll cause an IllegalStateException. As a remedy, you need to define how to override the value by providing a mergeFunction as the third argument of toMap(), or utilize the collector Collectors.groupingBy() instead to preserve all the values mapped to the same key.

魂牵梦绕锁你心扉 2025-02-03 06:15:21

无需制作另一个地图。您可以查询现有映射,以找到一个值包含目标字符串的键。

流在这里很有用来进行查询。

进行一些示例数据。

Map < String, Set < String > > map =
        Map.of(
                "laptops" , Set.of( "macbook" , "thinkpad" , "yoga" ) ,
                "desktops" , Set.of( "macmini" , "imac" , "otherDesktop" ) ,
                "smartphones" , Set.of( "iphone" , "galaxy5" , "oneplus" )
        );

你说:

dictionary.get(“ macbook”)将返回“笔记本电脑”

我们可以获取地图的所有条目。每个条目都是键值配对,我们的字符串导致一组字符串。

进行地图的条目流。

过滤条目,寻找任何价值(字符串集)包含我们的目标的任何条目,macBook。停止寻找比赛。

此结果在可选条目中。我们需要可选,因为可能没有找到,我们可能没有命中。

在您的例子的情况下,我们知道我们有命中率,因此请继续。我们知道找到的条目的值是包含我们目标的集合。因此,提取钥匙并报告。

Optional < Map.Entry < String, Set < String > > > entry =
        map
                .entrySet()
                .stream()
                .filter( ( Map.Entry < String, Set < String > > stringSetEntry ) -> stringSetEntry.getValue().contains( "macbook" ) )
                .findAny();
String result = entry.get().getKey();

请参阅此 code在indeone.com 中实时运行。

结果=笔记本电脑

No need to produce another map. You can query the existing map, to find a key whose value contains the target string.

Streams are useful here to make that query.

Make some example data.

Map < String, Set < String > > map =
        Map.of(
                "laptops" , Set.of( "macbook" , "thinkpad" , "yoga" ) ,
                "desktops" , Set.of( "macmini" , "imac" , "otherDesktop" ) ,
                "smartphones" , Set.of( "iphone" , "galaxy5" , "oneplus" )
        );

You said:

dictionary.get("macbook") would return "laptops"

We can get all the entries of a map. Each entry is a key-value pairing, our string leading to a set of strings.

Make a stream of the entries of the map.

Filter the entries, looking for any whose value (the set of strings) contains our target, macbook. Stop looking after finding a match.

The result of this in an Optional entry. We need Optional here because there may be none found, we may have no hits.

In this case of your example, we know we have a hit, so proceed. We know the found entry’s value is a set containing our target. So extract the key, and report.

Optional < Map.Entry < String, Set < String > > > entry =
        map
                .entrySet()
                .stream()
                .filter( ( Map.Entry < String, Set < String > > stringSetEntry ) -> stringSetEntry.getValue().contains( "macbook" ) )
                .findAny();
String result = entry.get().getKey();

See this code run live at IdeOne.com.

result = laptops

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