算法分析:
import java.util.*;
public class Knn {
/**
* 数据模型
*/
public static class KNNmodel{
public String name;
public int xuhao;
public double height;
public String type;
public double distance;
public double getDistance(){
return distance;
}
public KNNmodel(int xuhao,String name,double height,String type){
this.height=height;
this.name=name;
this.xuhao=xuhao;
this.type=type;
}
public String toString() {
return "KNNmodel{" +
" xuhao='" + xuhao + '\'' +
",name='" + name + '\'' +
", height=" + height +
", type='" + type + '\'' +
", distance=" + distance +
'}';
}
}
/**
* 计算距离并排序,取前K个数据
* @param lists
* @param newstudent
* @param k
* @return
*/
public static List<KNNmodel> calculate(List<KNNmodel> lists,KNNmodel newstudent,int k){
for (KNNmodel m:lists){
m.distance=Math.abs(m.height-newstudent.height);
}
Collections.sort(lists, Comparator.comparing(KNNmodel::getDistance));//按照每个元素的距离(即 distance 属性)进行升序排序
System.out.println("按距离排序后:");
for (KNNmodel list : lists) {
System.out.println(list);
}
List<KNNmodel> l=new ArrayList<>(k);
for (int i=0;i<k;i++){
l.add(lists.get(i));
}
return l;
}
//根据传入的列表 lists 中的数据统计每个类型出现的次数,并返回出现次数最多的类型
public static String findtype(List<KNNmodel> lists){
Map<String,Integer> map=new HashMap<>();
//通过遍历 lists 列表中的每个 KNNmodel 对象来更新 map 中的数据。
for (KNNmodel m:lists){
int sum= map.get(m.type)==null?1:map.get(m.type)+1;
map.put(m.type,sum);
}
System.out.println(map.toString());
List<Map.Entry<String,Integer>> list=new ArrayList<>(map.entrySet());
Collections.sort(list,Comparator.comparing(Map.Entry::getValue));//按照每个元素的值(即出现次数)进行升序排序
return list.get(list.size()-1).getKey();// 获取排序后的最后一个元素(出现次数最多的类型)
}
public static void main(String[] args) {
List<KNNmodel> lists=new ArrayList<KNNmodel>();
lists.add(new KNNmodel(1,"李丽",1.5,"矮"));
lists.add(new KNNmodel(2,"吉米",1.92,"高"));
lists.add(new KNNmodel(3,"马大华",1.7,"中等"));
lists.add(new KNNmodel(4,"王晓华",1.73,"中等"));
lists.add(new KNNmodel(5,"刘敏",1.6,"矮"));
lists.add(new KNNmodel(6,"张强",1.75,"中等"));
lists.add(new KNNmodel(7,"李秦",1.6,"矮"));
lists.add(new KNNmodel(8,"王壮",1.9,"高"));
lists.add(new KNNmodel(9,"刘冰",1.68,"中等"));
lists.add(new KNNmodel(10,"张喆",1.78,"中等"));
lists.add(new KNNmodel(11,"杨毅",1.70,"中等"));
lists.add(new KNNmodel(12,"徐田",1.68,"中等"));
lists.add(new KNNmodel(13,"高杰",1.65,"矮"));
lists.add(new KNNmodel(14,"张晓",1.78,"中等"));
KNNmodel newstudent=new KNNmodel(15,"易昌",1.70,"null");
int k=5;
List<KNNmodel> mindistance = calculate(lists, newstudent, k);
System.out.println("取前"+k+"个元组:");
for (KNNmodel knNmodel : mindistance) {
System.out.println(knNmodel);
}
String type = findtype(mindistance);
System.out.println(type);
}
}