从数据库取String的值存放到Map中 按汉字首字母分组排序并输出,类似二手车分类

效果如图:

导pinyin4j包:

<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j -->
<dependency>
    <groupId>com.belerweb</groupId>
    <artifactId>pinyin4j</artifactId>
    <version>2.5.0</version>
</dependency>

业务层读取首字母分组排序:

package cn.tcmp.service;
 
import cn.tcmp.entity.Vehicle;
import cn.tcmp.service.pinyin.PinYinService;
import com.alibaba.dubbo.config.annotation.Service;
import net.sourceforge.pinyin4j.PinyinHelper;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Date: 2019/9/20
 */
@Service
public class PinYinServiceImpl implements PinYinService {
 
//Vehicle为汽车实体类
    private static Map<String,List<Vehicle>> map = new HashMap<>();
 
    //提取字符串首字母
    @Override
    public String getPinYinHeadChar(String str) {
        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
 
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        return convert.substring(0,1).toUpperCase();
    }
    
    //首字母为Key list集合为Value 存到Map中
    @Override
    public Map<String, List<Vehicle>> getMap(List<Vehicle> list) {
        map.clear();
        for (Vehicle str : list) {
            if(map.containsKey(getPinYinHeadChar(str.getVehicleName()))) {
                List<Vehicle> list2 = map.get(getPinYinHeadChar(str.getVehicleName()));
                list2.add(str);
            }else {
                List<Vehicle> strlist = new ArrayList<>();
                strlist.add(str);
                map.put(getPinYinHeadChar(str.getVehicleName()).toUpperCase(), strlist);
            }
        }
        return map;
    }
}

控制层:

package cn.tcmp.controller.qianDuan;
 
import cn.tcmp.entity.DataDictionary;
import cn.tcmp.entity.Vehicle;
import cn.tcmp.service.CarQicheService;
import cn.tcmp.service.dataDictionary.DataDictionaryService;
import cn.tcmp.service.pinyin.PinYinService;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Date: 2019/9/20
 */
@Controller
@RequestMapping(value = "index")
public class CarIndexController {
 
    @Reference
    private CarQicheService qicheService;
    @Reference
    private PinYinService pinYinService;
 
    /**
     * 查询品牌 按首字母分类 到首页
     * @return
     */
    @RequestMapping(value = "queryVehicle",method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public String queryVehicle(){
        List<Object> arrayList = new ArrayList<>();
        //所有的品牌
        List<Vehicle> vehicles = qicheService.queryVehicleByVehicleName2("");
 
        /*for (Vehicle vehicle : vehicles) {
            System.err.println("品牌>>>>>"+vehicle);
        }*/
 
        //所有的车系
        List<Vehicle> list = qicheService.queryAllVehiclebyChexi();
 
        Map<String, List<Vehicle>> map = pinYinService.getMap(vehicles);
 
        /*for (Vehicle vehicle : list) {
            System.err.println("车系>>>>>"+vehicle);
        }
        for(Map.Entry<String, List<Vehicle>> entry : map.entrySet()){
            System.out.println("键 key :"+entry.getKey()+" 值value :"+entry.getValue());
        }*/
 
        //把品牌和车系放进集合里
        arrayList.add(list);
        arrayList.add(map);
        //返回
        return JSON.toJSONString(arrayList);
    }
 
}

前端js:

 
//页面js部分代码
window.onload=pinpaiUL();
 
function pinpaiUL(){
    $.post("/index/queryVehicle",function(result){
        //获取品牌的Map集合 并遍历
        var pinpai = result[1];
        $.each(pinpai,function (key,value) {
            //遍历Map中的value>>List集合
            //把首字母品牌放进去
 
            $("#youDian").append("<dl class='fore"+ key +"'><dt><a href='javascript:'>"+key+"</a></dt><dd id='dd"+key+"'></dd></dl>");
 
            $.each(value,function (i,val) {
                console.log("val>>"+val);
                //把8个品牌放到ul里
                if(val.vehicleID <= 8){
                    $("#pinPaiUL").append("<li><a href='javascript:'>"+val.vehicleName+"</a></li>");
                }
                $("#dd"+key).append("<em><a href=''>"+val.vehicleName+"</a></em>");
            })
        })
    })
}

K哥写法,看不懂。

 
/**
*以下为大佬K哥的写法 本人不太明白 看不懂
*/
//controller里直接写
//List<PinPai> list = this.service.queryAllPinPai();
 
List<PinPai> list = new ArrayList<>();
list.add(new PinPai("玛莎拉蒂"));
list.add(new PinPai("阿斯顿马丁"));
list.add(new PinPai("宾利"));
list.add(new PinPai("劳斯莱斯"));
 
//第一种写法
//Map<String,List<String>> result = list.stream().map(PinPai::getName).collect(Collectors.groupingBy(name -> {return getPinYinHeadChar(name);}));
//第二种写法
Map<string, List<string>>result=list. stream(). map(PinPai:: getName). collect(Collectors. groupingBy (Main:: getPinYinHeadchar));
 
for(Map.Entry<String,List<String>> entry : result.entrySet()){
    System.out.println(entry.getKey());
    System.out.println(entry.getValue());
}
 
//输出结果为
A
[阿斯顿马丁]
B
[宾利]
L
[劳斯莱斯]
M
[玛莎拉蒂]

版权声明:
作者:黯然gg
链接:https://3zi.cn/archives/124
来源:阿龙爱吃肉
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>