package com.ldj.cloud.user.demo;import java.util.*;/*** User: ldj* Date: 2024/5/11* Time: 10:03* Description: map按value降序*/
public class Tr {public static void main(String[] args) {ArrayList<String> list = new ArrayList<>();list.add("a");list.add("b");list.add("b");list.add("c");list.add("c");list.add("c");//去重分类Set<String> set = new HashSet<>(list);//为每一种元素,分配一个箩筐Map<String, Integer> map = new LinkedHashMap<>();set.forEach(ele -> {map.put(ele, 0);});//挑拣元素,如果同一种元素,放入对映的箩筐(+1)list.forEach((item -> {if (map.containsKey(item)) {map.put(item, map.get(item) + 1);}}));System.out.println(map);//map降序(重要)List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());entries.sort((o1, o2) -> o2.getValue() - o1.getValue());//找到数量最多那个元素System.out.println(entries);System.out.println(entries.get(0).getKey());System.out.println(entries.get(0).getValue());}}
代码优化
public static void main(String[] args) {ArrayList<String> list = new ArrayList<>();list.add("a");list.add("b");list.add("b");list.add("c");list.add("c");list.add("c");//去重分类 (伪代码)Rset当Redis的setSet<String> set = new HashSet<>(list);Map<String, Integer> map = new LinkedHashMap<>();list.forEach(item -> {map.put(item, map.get(item) != null ? (map.get(item) + 1) : 1);});System.out.println(map);}
借助Redis找出重复的元素