1 package ttt; 2 3 import java.nio.MappedByteBuffer; 4 import java.util.ArrayList; 5 import java.util.Collections; 6 import java.util.Comparator; 7 import java.util.HashMap; 8 import java.util.HashSet; 9 import java.util.List; 10 import java.util.Map; 11 import java.util.Map.Entry; 12 import java.util.Set; 13 import java.util.TreeMap; 14 import java.util.TreeSet; 15 16 public class list查重 { 17 18 public static void main(String[] args) { 19 20 List <String> wordList = new ArrayList<>(); 21 wordList.add("age"); 22 wordList.add("age"); 23 wordList.add("age"); 24 wordList.add("egg"); 25 wordList.add("dog"); 26 wordList.add("copy"); 27 wordList.add("copy"); 28 wordList.add("dog"); 29 wordList.add("dog"); 30 wordList.add("copy"); 31 wordList.add("battle"); 32 wordList.add("battle"); 33 wordList.add("battle"); 34 wordList.add("battle"); 35 wordList.add("battle"); 36 wordList.add("battle"); 37 wordList.add("age"); 38 39 rangeWords(wordList); 40 } 41 42 private static void rangeWords(List<String> wordList) { 43 Set<String> uniqueSet = new HashSet<>(wordList); 44 Map<String,Integer> maap= new HashMap<>(); 45 for (String temp : uniqueSet) { 46 int num = Collections.frequency(wordList, temp); 47 maap.put(temp, num); 48 } 49 List<Entry<String,Integer>> list = new ArrayList<>(maap.entrySet()); 50 Collections.sort(list, new Comparator<Map.Entry<String,Integer>>() { 51 @Override 52 public int compare(Map.Entry<String,Integer> cmap,Map.Entry<String,Integer> cmap2){ 53 return cmap2.getValue()-cmap.getValue(); 54 } 55 }); 56 57 printMap(list); 58 } 59 60 private static void printMap(List<Entry<String, Integer>> list) { 61 for (Map.Entry entry : list) { 62 System.out.println(entry.getKey()+" "+entry.getValue()); 63 } 64 } 65 66 }
时间: 2024-10-25 11:50:57