public class Main {
public List<String> sortAccordingly(List<String> unsortedList ) {
List<String> sorted=new ArrayList<>();
Map<String,Integer> freq=new TreeMap();
for(String s:unsortedList) {
Map<Character, Integer> fq = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (fq.containsKey(s.charAt(i)))
fq.replace(s.charAt(i), fq.get(s.charAt(i)) + 1);
else
fq.put(s.charAt(i), 1);
}
freq.put(s, Collections.max(fq.values()));
}
Map<String,Integer> sortedOne=freq.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(e1,e2)->e1,LinkedHashMap::new));
sortedOne.putAll(freq);
sorted.addAll(sortedOne.keySet());
return sorted;
}
public static void main(String[] args) {
List <String> list=new ArrayList<>();
list.add("apple");
list.add("orange");
list.add("banana");
System.out.println(new Main().sortAccordingly(list));
}
}
Вы можете использовать компаратор
Comparator<String> valueCompare=new Comparator<String>() {
@Override
public int compare(String s, String t1) {
return freq.get(s).compareTo(freq.get(t1));
}
};
вместо
Map<String,Integer> sortedOne=freq.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue,(e1,e2)->e1,LinkedHashMap::new));
после того, как эта функция будет
public List<String> sortAccordingly(List<String> unsortedList ) {
List<String> sorted=new ArrayList<>();
Map<String,Integer> freq=new TreeMap();
Comparator<String> valueCompare=new Comparator<String>() {
@Override
public int compare(String s, String t1) {
return freq.get(s).compareTo(freq.get(t1));
}
};
for(String s:unsortedList) {
Map<Character, Integer> fq = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (fq.containsKey(s.charAt(i)))
fq.replace(s.charAt(i), fq.get(s.charAt(i)) + 1);
else
fq.put(s.charAt(i), 1);
}
freq.put(s, Collections.max(fq.values()));
}
Map<String,Integer> sortedOne=new TreeMap<>(valueCompare);
sortedOne.putAll(freq);
sorted.addAll(sortedOne.keySet());
return sorted;
}