Map排序相关操作

Map排序相关操作

当我们需要对Map进行排序优先考虑TreeMap。而要对HashMap排序可以考虑将HashMap转化成TreeMap。

HashMap转化TreeMap

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
  public static void main(String[] a) {
    Map<String, String> hmap = new HashMap<String, String>();
    hmap.put("1", "one");
    gmap.put("2", "two");
    gmap.put("3", "three");

    Map<String, String> tmap = new TreeMap<String, String>(hmap);
  	//将HashMap以值的形式传入TreeMap
  }
}

迭代器迭代TreeMap

map比较特殊没有继承interator接口,不能直接迭代,所以我们需要将他的key值转化为Set,然后对Set进行迭代。
注意:map调用keySet();将map的键转化为set,keySet()是单例模式,我们改变一个keySet()里的值,其它的也会改变。

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

public class TreeMapTest {
	public static void main(String[] args) {
		Map<Integer,String> tmap = new TreeMap<>();
		tmap.put(1, "a");
		tmap.put(2, "b");
		tmap.put(4, "d");
		tmap.put(5, "e");
		tmap.put(3, "c");
		
		
		for(Iterator<Integer> it = tmap.keySet().iterator(); it.hasNext();) {
			System.out.println(tmap.get(it.next()));
		}
	}

}
/*结果:
a
b
c
d
e
*/

根据value值排序

实现思路:把map的Entry对象存入List集合,再用Collections.sort(List l, Comparator c)方法排序

	Map<String, Integer> map = new HashMap<String, Integer>();

	List<Entry<String,Integer>> list =
    new ArrayList<Entry<String,Integer>>(map.entrySet());
//set转list,把set当作参数。
	
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
    public int compare(Map.Entry<String, Integer> o1,
            Map.Entry<String, Integer> o2) {
        return (o2.getValue() - o1.getValue());
    }
});

题目案例

在这里插入图片描述

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class TestMap {
	private static String str;
	public static void main(String[] args) {
		str="I propose to consider the question,"
				+ " \"Can machines think?\""
				+ " This should begin with definitions of the meaning of the terms "
				+ "\"machine\" and \"think.\""
				+ " The definitions might be framed so as to reflect so far as possible the normal use of the words, but this attitude is dangerous,"
				+ " If the meaning of the words \"machine\" and \"think\" "
				+ "are to be found by examining how they are commonly used it is difficult to escape the conclusion that the meaning and the answer to the question, "
				+ "\"Can machines think?\" is to be sought in a statistical survey such as a Gallup poll."
				+ " But this is absurd. "
				+ "Instead of attempting such a definition I shall replace the question by another,"
				+ " which is closely related to it and is expressed in relatively unambiguous words.";
				
		List<String> words = getWords();
		Map<String,Integer> map = new TreeMap<>();
		int n = 0;
		for(String word:words) {
			if(map.containsKey(word)) {
				 n = map.get(word);
				 n+=1;
				 map.put(word, n);
				 n = 0;
			}else {
				map.put(word, 1);
			}
		}
		
		List<Entry<String,Integer>> list = new ArrayList<Entry<String,Integer>>(map.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
		    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
		        return (o2.getValue() - o1.getValue());
		    }
		});
		
		for(Entry<String,Integer> entry:list) {
			System.out.println(entry.getKey()+":"+entry.getValue());
		}
	}
	
	private static List<String> getWords() {
		List<String> words = new ArrayList<>();
		int n=0;
		for(int i=0;i<str.length();i++) {
			char c =str.charAt(i);
			if((c<'a'||c>'z')&&(c<'A'||c>'Z')) {
				if(i==n) {
					n+=1;
					continue;
				}
				words.add(str.substring(n, i));
				n = i+1;
			}
		}
		return words;
	}

}

/*结果:
the:12
to:7
is:6
of:5
and:4
think:4
a:3
as:3
be:3
meaning:3
question:3
words:3
Can:2
I:2
are:2
by:2
definitions:2
in:2
it:2
machine:2
machines:2
so:2
such:2
this:2
But:1
Gallup:1
If:1
Instead:1
The:1
This:1
absurd:1
another:1
answer:1
attempting:1
attitude:1
begin:1
but:1
closely:1
commonly:1
conclusion:1
consider:1
dangerous:1
definition:1
difficult:1
escape:1
examining:1
expressed:1
far:1
found:1
framed:1
how:1
might:1
normal:1
poll:1
possible:1
propose:1
reflect:1
related:1
relatively:1
replace:1
shall:1
should:1
sought:1
statistical:1
survey:1
terms:1
that:1
they:1
unambiguous:1
use:1
used:1
which:1
with:1

*/
stream map排序是指使用Stream API中的map方法对数据进行转换,并按照指定的比较规则对转换后的结果进行排序。 在给定的引用中,提到了使用Stream的map方法来获取所有的name,并输出结果。这是一个简单的例子,展示了如何使用map方法来对元素进行转换。 如果我们想要对转换后的结果进行排序,可以使用Stream的sorted方法。该方法接受一个Comparator对象作为参数,以指定排序规则。比如,我们可以使用Comparator.comparing方法指定根据name属性进行排序。 以下是一个示例代码: ``` list.stream() .map(Account::getName) .sorted(Comparator.comparing(String::toLowerCase)) // 根据name属性进行排序 .forEach(System.out::println); ``` 上述代码中,首先使用map方法获取所有的name属性,然后使用sorted方法对转换后的结果进行排序,最后使用forEach方法打印排序后的结果。 请注意,这只是一个简单的示例,您可以根据具体需求自定义Comparator对象来进行更复杂的排序操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [java1.8Stream map、复杂排序,集合转换等常用操作,优雅值拉满](https://blog.csdn.net/John_D_B_Lee/article/details/115407983)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值