Java——Map、IO流练习

用代码实现以下需求
(1)有如下字符串"If you want to change your fate I think you must come to the dark horse to learn java"(用空格间隔)
(2)打印格式:

to=3
think=1
you=2 /
/…

(3)按照上面的打印格式将内容写入到D:\count.txt文件中(要求用高效流)

实现代码:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class HomeWork1 {
	public static void main(String[] args) throws IOException {
		String s = "If you want to change your fate I think you must come to the dark horse to learn java";
		function(s);
	}
	public static void function(String s) throws IOException {
		String[] sArr = s.split(" ");
		HashMap<String, Integer> hm = new HashMap<>();
		
		for(String string : sArr) {
			if(!hm.containsKey(string))
				hm.put(string, 1);
			else {
				int value = hm.get(string);
				value++;
				hm.put(string, value);
			}
		}
		List<String> list = new ArrayList<>();//新建一个过度数组储存单词
		for(String key : hm.keySet()) {
			list.add(key);
		}
		Collections.sort(list);//将储存的单词排序
		Map<String, Integer> orderMap = new LinkedHashMap<String, Integer>();//新建一个有序的LinkedHashMap
		for(String key : list) {
			orderMap.put(key, hm.get(key));//按顺序将排序后的单词和对应个数存入LinkedHashMap中
		}
		write(orderMap);
	}
	//
	public static void write(Map<String, Integer> map) throws IOException {
		BufferedWriter bfw = new BufferedWriter(new FileWriter("D:\\360MoveData\\Users\\xucc\\Desktop\\count.txt"));
		for(String key : map.keySet()) {
			bfw.write(key+"="+map.get(key));
			bfw.newLine();//写入一个,换一行
			bfw.flush();
		}
		bfw.close();
	}
}

输出结果:在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值