Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count and sort repeating strings

i have got a string of names

String str = "A. Walker, L. Gordon, C. Riley, L. Gordon";

I need to count name occurancies and sort the occurancies from biggest to lowest.

I have done the countung part, but I also need to sort it.

String[] array = str.split(", ");        

List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);
for(String s: mySet)
    System.out.println(s + " " +Collections.frequency(asList,s));

Output should look like this

L. Gordon 2, A. Walker 1, C. Riley 1
like image 795
John Greg Avatar asked Jun 29 '26 21:06

John Greg


2 Answers

You can do something like this:

public class Test {
    static class NameFreq {
        public NameFreq(String name, int freq) {
            this.name = name;
            this.freq = freq;
        }
        String name;
        int freq;
        @Override
        public String toString() {
            return name + " " + freq;
        }
    }
    public static void main(String[] args) throws Exception {
        String str = "A. Walker, L. Gordon, C. Riley, L. Gordon";
        Map<String, NameFreq> map = new HashMap<>();
        String[] array = str.split("\\s*,\\s*");
        for(String name : array) {
            NameFreq nameFreq = map.get(name);
            if( nameFreq==null )
                map.put(name, new NameFreq(name, 1));
            else
                nameFreq.freq++;
        }

        List<NameFreq> list = new ArrayList<>(map.values());
        Collections.sort(list, new Comparator<NameFreq>() {
            @Override
            public int compare(NameFreq o1, NameFreq o2) {
                return Integer.compare(o2.freq, o1.freq);
            }
        });

        System.out.println(list);
        //output: [L. Gordon 2, A. Walker 1, C. Riley 1]
    }
}
like image 163
yavuzkavus Avatar answered Jul 02 '26 09:07

yavuzkavus


You can easily do it with stream, e.g.:

String str = "A. Walker, L. Gordon, C. Riley, L. Gordon";
TreeMap<String,Long> data = Arrays.stream(str.split(","))
    .map(s -> s.trim())
    .collect(Collectors.groupingBy(Function.identity(), TreeMap::new, Collectors.counting()));

LinkedHashMap<String,Long> resultMap= data.entrySet().stream()

.sorted(Map.Entry.comparingByValue().reversed()) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); System.out.println(resultMap);

If you want to strip out curly braces from the beginning and end of string, you can use substring, e.g.:

String result = resultMap.toString();
if(result.length > 2){
   result = result.substring(1, result.length() - 1);
}
System.out.println(result);
like image 35
Darshan Mehta Avatar answered Jul 02 '26 09:07

Darshan Mehta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!