62,614
社区成员
发帖
与我相关
我的任务
分享
final String value = "BBAACCC";
String result = value.chars().mapToObj(v->(char)v).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream().sorted((e1, e2)->{
int compare = Long.compare(e2.getValue(), e1.getValue());
return compare == 0 ? Character.compare(e2.getKey(), e1.getKey()) : compare;
}).map(e->String.valueOf(e.getKey()) + e.getValue()).collect(Collectors.joining());
System.out.println(result);
final String value = "BBAACCC";
String result = value.chars().mapToObj(v->(char)v).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream().sorted((e1, e2)->{
int compare = Long.compare(e2.getValue(), e1.getValue());
return compare == 0 ? Character.compare(e2.getKey(), e1.getKey()) : compare;
}).map(e->String.valueOf(e.getKey()) + e.getValue()).collect(Collectors.joining());
System.out.println(result);
先将字符串转换成字符流,
然后分组计数,
然后排序,
然后将排序结果转成字符串,
然后拼接,得到结果。public static void main(String[] args) {
String s="BBAACCC";
List<String> strings = Arrays.asList(s.split(""));
Map<String, Long> collect = strings.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<String, Long> result = new TreeMap<String, Long>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
// 降序排序
return obj2.compareTo(obj1);
}
});
for (String item:
collect.keySet()) {
result.put(item,collect.get(item));
}
System.out.println(result);
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Collectors;
public class StreamDemo {
public static void main(String[] args) {
String str = "AABBCCCD";
List<String> list = Arrays.asList(str.split(""));
Map<String, Long> map1 = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<String, Long> map2 = new TreeMap<String, Long>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (map1.get(o2).equals(map1.get(o1))) {
return o2.compareTo(o1);
}
return map1.get(o2).compareTo(map1.get(o1));
}
});
map2.putAll(map1);
for (Entry<String, Long> entry : map2.entrySet()) {
System.out.printf("%s%d", entry.getKey(), entry.getValue());
}
System.out.printf("%n");
}
}