根据嵌套在给定的hashmap内部的每个hashmap的大小,按顺序打印hashmap的内容

发布于 2025-02-11 04:32:03 字数 1128 浏览 2 评论 0原文

我在hashmap内有一个hashmap。我想根据内部hashmap中的元素大小在hashmap中打印元素。因此,元素数量最多的元素应首先打印。我是新来的hashmap,被卡住了。

这是hashmap以及我如何打印它:

Map<String, Map<String, Integer>> states = new ConcurrentHashMap<String, Map<String, Integer>>();

for(Entry<String, Map<String, Integer>> entry : states.entrySet()) {

    System.out.println("State:" + entry.getKey());

    Map<String, Integer> tempMap = entry.getValue();

    for(Entry<String, Integer> innerEntry : tempMap.entrySet()) {
        System.out.println("City:" + innerEntry.getKey() + " Count:" + innerEntry.getValue());
    }
    
    System.out.println();
}

我当前获取的输出:

State:Texas
City:Austin Count:1

State:Hawaii
City:Honolulu Count:1
City:Kihei Count:1
City:Maui Count:1

State:California
City:Newport Beach Count:1

我需要的输出:

State:Hawaii
City:Honolulu Count:1
City:Kihei Count:1
City:Maui Count:1

State:Texas
City:Austin Count:1

State:california
City:Newport Beach Count:1

I have a HashMap inside a HashMap. I want to print the elements in the HashMap according to the size of elements in the inner HashMap. So the element with the highest number of elements should print first. I'm new to HashMaps and got stuck.

This is the HashMap and how I'm printing it:

Map<String, Map<String, Integer>> states = new ConcurrentHashMap<String, Map<String, Integer>>();

for(Entry<String, Map<String, Integer>> entry : states.entrySet()) {

    System.out.println("State:" + entry.getKey());

    Map<String, Integer> tempMap = entry.getValue();

    for(Entry<String, Integer> innerEntry : tempMap.entrySet()) {
        System.out.println("City:" + innerEntry.getKey() + " Count:" + innerEntry.getValue());
    }
    
    System.out.println();
}

The output that I'm currently getting:

State:Texas
City:Austin Count:1

State:Hawaii
City:Honolulu Count:1
City:Kihei Count:1
City:Maui Count:1

State:California
City:Newport Beach Count:1

The output I need:

State:Hawaii
City:Honolulu Count:1
City:Kihei Count:1
City:Maui Count:1

State:Texas
City:Austin Count:1

State:california
City:Newport Beach Count:1

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

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

发布评论

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

评论(6

疯了 2025-02-18 04:32:03

Hashmap无法维护订单,因此您无法对其进行排序。

您可以将地图内容转储到列表中,并使用自定义比较器对其进行排序。但是您缺少一些东西 - 构造数据的方式是错误的, state cities state 是两个信息彼此密切相关。使用地图将它们结合在一起是滥用收藏品,这使您的代码僵化且无法实现。

使用对象的力量,

您的代码不会自动成为面向对象的因素,因为您使用的是面向对象的语言。

正确的方法是定义状态city作为类,并维护状态>状态对象的列表,而不是处理嵌套 map

class State {
    private String name;
    private List<City> cities = new ArrayList<>();
    
    public State(String name) {
        this.name = name;
    }
    
    public void addCity(City city) {
        cities.add(city);
    }
    
    public boolean removeCity(City city) {
        return cities.remove(city);
    }
    
    public List<City> getCities() {
        return cities;
    }
    
    @Override
    public String toString() {
        return "State:" + name + "\n" +
            cities.stream()
                .map(City::toString)
                .collect(Collectors.joining("\n"))
            + "\n";
    }
}

class City {
    private String name;
    private int count;
    
    public City(String name, int count) {
        this.name = name;
        this.count = count;
    }
    
    @Override
    public String toString() {
        return "City:" + name + " Count:" + count;
    }
}

这就是您可以在客户端代码中使用此类的方式:

public static void main(String[] args) {
    List<State> states = new ArrayList<>();
    State texas = new State("Texas");
    texas.addCity(new City("Austin", 1));
    
    State hawaii = new State("Hawaii");
    hawaii.addCity(new City("Honolulu", 1));
    hawaii.addCity(new City("Kihei", 1));
    hawaii.addCity(new City("Maui", 1));
    
    State california = new State("California");
    california.addCity(new City("Newport Beach", 1));
    
    Collections.addAll(states, texas, hawaii, california);
    
    states.sort(Comparator.<State>comparingInt(state -> state.getCities().size()).reversed());
    
    for (State state: states) {
        System.out.println(state);
    }
}

输出:

State:Hawaii
City:Honolulu Count:1
City:Kihei Count:1
City:Maui Count:1

State:Texas
City:Austin Count:1

State:California
City:Newport Beach Count:1

HashMap is not capable of maintaining the order, therefore you can't sort it.

You can dump the map contents into a list and sort it using a custom comparator. But there's something that you're missing - the way you're structuring the data is wrong, state and cities that belong to that state are two pieces of information are closely related to each other. Using a map to combine them together is an abuse of collections, it makes your code rigid and unmaintainable.

Use the power of Objects

Your code doesn't become object-oriented automatically because of the fact that you're using an object-oriented language.

The correct approach would be to define State and City as classes and maintain a list of State objects instead of dealing with a nested map.

class State {
    private String name;
    private List<City> cities = new ArrayList<>();
    
    public State(String name) {
        this.name = name;
    }
    
    public void addCity(City city) {
        cities.add(city);
    }
    
    public boolean removeCity(City city) {
        return cities.remove(city);
    }
    
    public List<City> getCities() {
        return cities;
    }
    
    @Override
    public String toString() {
        return "State:" + name + "\n" +
            cities.stream()
                .map(City::toString)
                .collect(Collectors.joining("\n"))
            + "\n";
    }
}

class City {
    private String name;
    private int count;
    
    public City(String name, int count) {
        this.name = name;
        this.count = count;
    }
    
    @Override
    public String toString() {
        return "City:" + name + " Count:" + count;
    }
}

That's how you can use this classes in the client code:

public static void main(String[] args) {
    List<State> states = new ArrayList<>();
    State texas = new State("Texas");
    texas.addCity(new City("Austin", 1));
    
    State hawaii = new State("Hawaii");
    hawaii.addCity(new City("Honolulu", 1));
    hawaii.addCity(new City("Kihei", 1));
    hawaii.addCity(new City("Maui", 1));
    
    State california = new State("California");
    california.addCity(new City("Newport Beach", 1));
    
    Collections.addAll(states, texas, hawaii, california);
    
    states.sort(Comparator.<State>comparingInt(state -> state.getCities().size()).reversed());
    
    for (State state: states) {
        System.out.println(state);
    }
}

Output:

State:Hawaii
City:Honolulu Count:1
City:Kihei Count:1
City:Maui Count:1

State:Texas
City:Austin Count:1

State:California
City:Newport Beach Count:1
朮生 2025-02-18 04:32:03

由于 concurrenthashmap 不保证订购,因此您必须对地图进行分类,然后将其排序,然后将其整理到A linkedhashmap

Map<String, Map<String, Integer>> sortedStates = new LinkedHashMap<String, Map<String, Integer>>();
states.entrySet().stream()
        .sorted(new Comparator<Map.Entry<String, Map<String, Integer>>>() {
            public int compare(Map.Entry<String, Map<String, Integer>> mapA, Map.Entry<String, Map<String, Integer>> mapB){
                return mapB.getValue().size() - mapA.getValue().size();
              }
            })
        .forEachOrdered(mapInner -> sortedStates.put(mapInner.getKey(), mapInner.getValue()));

Since ConcurrentHashMap makes no guarantees about ordering, you have to sort your map be getting entrySet and sort them then re-put into a LinkedHashMap

Map<String, Map<String, Integer>> sortedStates = new LinkedHashMap<String, Map<String, Integer>>();
states.entrySet().stream()
        .sorted(new Comparator<Map.Entry<String, Map<String, Integer>>>() {
            public int compare(Map.Entry<String, Map<String, Integer>> mapA, Map.Entry<String, Map<String, Integer>> mapB){
                return mapB.getValue().size() - mapA.getValue().size();
              }
            })
        .forEachOrdered(mapInner -> sortedStates.put(mapInner.getKey(), mapInner.getValue()));
ㄖ落Θ余辉 2025-02-18 04:32:03
  1. 创建一个size_map-&gt; MAP&LT; INTEGER,LIST&GT; size_map = new hashmap&lt; integer,list&gt;();
  • 这是将存储城市数量存储为钥匙,并将其视为值。请注意,此处已存储在列表中,因为多个状态可以具有相同数量的城市。
  1. 通过点1中的映射键制作列表(size_list)。(密钥是不同状态的城市数)。以降序订购此列表

  2. 订购此列表,将size_list用作查找,并获取具有当前size_map hashmap的当前大小的状态列表。基本上使用size_list作为查找。

注意 - 这将增加您的开销,并且性能可能不佳。

    Map<String, Map<String, Integer>> states = new ConcurrentHashMap<String, Map<String, Integer>>();

    //create size HashMap -- store number of cities as key and value would be list of states 
    Map<Integer, List<String>> size_map = new HashMap<Integer, List<String>>();

    for(Map.Entry<String, Map<String, Integer>> entry : states.entrySet())
    {
        int size = entry.getValue().size();
        String state = entry.getKey();
        if(size_map.containsKey(size))
        {
            List<String> retreived_list = size_map.get(size);
            retreived_list.add(state);
            size_map.put(size, retreived_list);
        }
        else
        {
            List<String> retreived_list = new ArrayList<String>();
            retreived_list.add(state);
            size_map.put(size, retreived_list);
        }
    }

    //create a list out of size_map keys and sort it in descending order
    List<Integer> size_list = new ArrayList<Integer>(size_map.keySet());
    Collections.sort(size_list, Collections.reverseOrder());

    //index will be current index in size_list, fetch states list from size_map and look for the same state in the original "state" hashmap
    int index =0;
    for(Map.Entry<String, Map<String, Integer>> entry : states.entrySet())
    {
        int current_size = size_list.get(index);
        List<String> states_list = size_map.get(current_size);

        for(String s : states_list)
        {
            System.out.println("State:" + s);
            Map<String, Integer> tempMap = states.get(s);
            for(Map.Entry<String, Integer> innerEntry : tempMap.entrySet()) {
                System.out.println("City:" + innerEntry.getKey() + " Count:" + innerEntry.getValue());
            }
        }
        index++;
        System.out.println();
    }
  1. create a size_map -> Map<Integer, List> size_map = new HashMap<Integer, List>();
  • This is to store store number of cities as key and states as the value. Note here states are stored in a list because multiple states can have same number of cities.
  1. Make a list (size_list) out of keys of map in point 1. (Keys are number of cities for different states). Order this list in descending order

  2. While iterating your "states" Hashmap, use size_list as a lookup and fetch the list of states with the current size from size_map HashMap. Basically use size_list as a lookup.

Note - this will increase your overhead and performance might not be great.

    Map<String, Map<String, Integer>> states = new ConcurrentHashMap<String, Map<String, Integer>>();

    //create size HashMap -- store number of cities as key and value would be list of states 
    Map<Integer, List<String>> size_map = new HashMap<Integer, List<String>>();

    for(Map.Entry<String, Map<String, Integer>> entry : states.entrySet())
    {
        int size = entry.getValue().size();
        String state = entry.getKey();
        if(size_map.containsKey(size))
        {
            List<String> retreived_list = size_map.get(size);
            retreived_list.add(state);
            size_map.put(size, retreived_list);
        }
        else
        {
            List<String> retreived_list = new ArrayList<String>();
            retreived_list.add(state);
            size_map.put(size, retreived_list);
        }
    }

    //create a list out of size_map keys and sort it in descending order
    List<Integer> size_list = new ArrayList<Integer>(size_map.keySet());
    Collections.sort(size_list, Collections.reverseOrder());

    //index will be current index in size_list, fetch states list from size_map and look for the same state in the original "state" hashmap
    int index =0;
    for(Map.Entry<String, Map<String, Integer>> entry : states.entrySet())
    {
        int current_size = size_list.get(index);
        List<String> states_list = size_map.get(current_size);

        for(String s : states_list)
        {
            System.out.println("State:" + s);
            Map<String, Integer> tempMap = states.get(s);
            for(Map.Entry<String, Integer> innerEntry : tempMap.entrySet()) {
                System.out.println("City:" + innerEntry.getKey() + " Count:" + innerEntry.getValue());
            }
        }
        index++;
        System.out.println();
    }
自由范儿 2025-02-18 04:32:03

您可以在打印出来之前使用Streams API进行排序:

Comparator<Entry<String, Map<String, Integer>>> entryComparator =
        Comparator.comparingInt((Entry<String, Map<String, Integer>> entryOne) -> entryOne.getValue().size());

    for(Entry<String, Map<String, Integer>> entry : states.entrySet().stream().sorted(entryComparator.reversed()).collect(
        Collectors.toList())) {
      System.out.println("State:" + entry.getKey());
      Map<String, Integer> tempMap = entry.getValue();
      for(Entry<String, Integer> innerEntry : tempMap.entrySet()) {
        System.out.println("City:" + innerEntry.getKey() + " Count:" + innerEntry.getValue());
      }

      System.out.println();
    }

You can use Streams API for sorting before print it out:

Comparator<Entry<String, Map<String, Integer>>> entryComparator =
        Comparator.comparingInt((Entry<String, Map<String, Integer>> entryOne) -> entryOne.getValue().size());

    for(Entry<String, Map<String, Integer>> entry : states.entrySet().stream().sorted(entryComparator.reversed()).collect(
        Collectors.toList())) {
      System.out.println("State:" + entry.getKey());
      Map<String, Integer> tempMap = entry.getValue();
      for(Entry<String, Integer> innerEntry : tempMap.entrySet()) {
        System.out.println("City:" + innerEntry.getKey() + " Count:" + innerEntry.getValue());
      }

      System.out.println();
    }
悲凉≈ 2025-02-18 04:32:03

Hashmap不保证地图的顺序;特别是,它不能保证随着时间的流逝,订单将保持恒定。
改用LinkedHashMap,这看起来像:

Map sortedMap = new LinkedHashMap();
originalHashMap.entrySet().stream()
     .sorted(Comparator.comparingInt(e -> e.getValue().size()))
     .forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));

现在,预期排序的映射为SortedMap

HashMap makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Using LinkedHashMap instead and that will look like:

Map sortedMap = new LinkedHashMap();
originalHashMap.entrySet().stream()
     .sorted(Comparator.comparingInt(e -> e.getValue().size()))
     .forEachOrdered(e -> sortedMap.put(e.getKey(), e.getValue()));

Now, expected sorted map is sortedMap

何处潇湘 2025-02-18 04:32:03

尝试一下。

Map<String, Map<String, Integer>> states = new ConcurrentHashMap<String, Map<String, Integer>>();
states.put("Texas", Map.of("Austin", 1));
states.put("Hawaii", Map.of("Honolulu", 1, "Kihei", 1, "Maui", 1));
states.put("California", Map.of("Newport Beach", 1)); 

states.entrySet().stream()
    .sorted(Comparator.comparing(e -> -e.getValue().size()))
    .forEach(e -> {
        System.out.println("State:" + e.getKey());
        e.getValue().entrySet().stream()
            .forEach(f -> System.out.println("City:" + f.getKey() + " Count:" + f.getValue()));
        System.out.println();
    });

输出:

State:Hawaii
City:Maui Count:1
City:Honolulu Count:1
City:Kihei Count:1

State:Texas
City:Austin Count:1

State:California
City:Newport Beach Count:1

Try this.

Map<String, Map<String, Integer>> states = new ConcurrentHashMap<String, Map<String, Integer>>();
states.put("Texas", Map.of("Austin", 1));
states.put("Hawaii", Map.of("Honolulu", 1, "Kihei", 1, "Maui", 1));
states.put("California", Map.of("Newport Beach", 1)); 

states.entrySet().stream()
    .sorted(Comparator.comparing(e -> -e.getValue().size()))
    .forEach(e -> {
        System.out.println("State:" + e.getKey());
        e.getValue().entrySet().stream()
            .forEach(f -> System.out.println("City:" + f.getKey() + " Count:" + f.getValue()));
        System.out.println();
    });

output:

State:Hawaii
City:Maui Count:1
City:Honolulu Count:1
City:Kihei Count:1

State:Texas
City:Austin Count:1

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