Mikhail Nono
Mikhail Nono

Reputation: 93

How to get data (key,value) from ListArray

I use the code to Sort the data in the map.

 Map<Integer, Integer> map = new HashMap<>();
    List list = new ArrayList(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
        @Override
        public int compare(Map.Entry<Integer, Integer> a, Map.Entry<Integer, Integer> b) {
            return a.getValue() - b.getValue();
        }
    });

I just copy the data from map to List and sort it. How can I get the data from the List? The method get() of list returns just the object, not my 2 integers

Upvotes: 1

Views: 398

Answers (2)

Vasu
Vasu

Reputation: 22452

Your list actually contains elements of type Map.Entry<Integer, Integer>, so you can retrieve the each Entry as shown below:

Map<Integer, Integer> map = new HashMap<>();
//add the values to map here

//Always prefer to use generic types shown below (instead of raw List)
List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());

Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
  @Override
  public int compare(Map.Entry<Integer, Integer> a,
                  Map.Entry<Integer, Integer> b){
                       return a.getValue() - b.getValue();
    }
  });

  //loop over the list to retrieve the list elements
  for(Map.Entry<Integer, Integer> entry : list) {
        System.out.println(entry.getValue());
  }

Upvotes: 1

davidxxx
davidxxx

Reputation: 131526

You do that :

 List list = new ArrayList(map.entrySet());

You could use generics in your list and then iterate on the Entry of the list after your sorted it:

List<Entry<Integer, Integer>> list = new ArrayList(map.entrySet());
...
// your sort the list
..
// you iterate on key-value
for (Entry<Integer, Integer> entry : list){
  Integer key =  entry.getKey();
  Integer value =  entry.getValue();
}

Upvotes: 1

Related Questions