当前位置:Gxlcms > 数据库问题 > 基础算法7:从数据库某个字段中取出现次数最多的几条数据形成“热门xxx”

基础算法7:从数据库某个字段中取出现次数最多的几条数据形成“热门xxx”

时间:2021-07-01 10:21:17 帮助过:36人阅读

技术分享

在这里,我们需要查出所有的“出发城市”和“到达城市”,并对每个城市进行计数根据其出现次数来取出几个出现次数最多的城市为热门城市

注:将多个字段的数据合并在一起并且不经过去重处理,可以使用下面这个SQL语句:

select DEPARTURE_AIRPORT from USR_AIR_LINE union all select ARRIVAL_AIRPORT from USR_AIR_LINE;

(2)对取出的数据进行计数,排序以及求出最后的“热门城市”:

package cn.zifangsky.base;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class PopAirportDemo {

	public static void main(String[] args) throws Exception {
		// 读文件
		BufferedReader reader = new BufferedReader(
				new FileReader(new File("C:/Users/Administrator/Desktop/airport.txt")));
		String temp = "";
		List<String> airportCodes = new ArrayList<String>(); // 城市三字码集合

		while ((temp = reader.readLine()) != null) {
			airportCodes.add(temp);
		}
		reader.close();

		Map<String, Integer> countMap = new HashMap<String, Integer>();  //<城市三字码,总次数>
		//遍历List形成<城市三字码,总次数>键值对
		for (String code : airportCodes) {
			if (!countMap.containsKey(code)) {
				countMap.put(code, 1);
			} else {
				countMap.put(code, countMap.get(code) + 1);
			}

		}

		// 排序
		List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(countMap.entrySet());
		Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
			//自定义排序
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
				return o2.getValue().compareTo(o1.getValue());
			}
		});

		List<String> result = new ArrayList<String>();  //热门城市集合
		int point = 0;
		for (Map.Entry<String, Integer> mapping : list) {
			// System.out.println(mapping.getKey() + " -> " +
			// mapping.getValue());
			result.add(mapping.getKey());
			point++;
			//这里取5个热门城市
			if (point >= 5)
				break;
		}

		System.out.println(result);
	}

}

注:我这里为了简化操作,已经把所有的城市三字码保存到“airport.txt”这个文件中了,这里只专注于整个算法流程而不考虑JDBC等问题


本文出自 “zifangsky的个人博客” 博客,请务必保留此出处http://983836259.blog.51cto.com/7311475/1772447

基础算法7:从数据库某个字段中取出现次数最多的几条数据形成“热门xxx”

标签:热门 算法

人气教程排行