grouping List of Objects and counting using Java collection -


which java collection class better group list of objects?

i have list of messages users below:

aaa hi bbb hello ccc gm aaa  can? ccc   yes ddd   no 

from list of message object want count , display aaa(2)+bbb(1)+ccc(2)+ddd(1). code help?

putting pieces couple of other answers, adapting code other question , fixing few trivial errors:

    // want sorted list of keys, should use treemap     map<string, integer> stringswithcount = new treemap<>();     (message msg : convinfo.messages) {         // ever input comes from: turn lower case,         // "ccc" , "ccc" go same counter         string item = msg.username.tolowercase();         if (stringswithcount.containskey(item)) {             stringswithcount.put(item, stringswithcount.get(item) + 1);         } else {             stringswithcount.put(item, 1);         }     }     string result = stringswithcount             .entryset()             .stream()             .map(entry -> entry.getkey() + '(' + entry.getvalue() + ')')             .collect(collectors.joining("+"));     system.out.println(result); 

this prints:

aaa(2)+bbb(1)+ccc(2)+ddd(1) 

Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -