Boostr



0 votes
9 views
import java.util.ArrayList;

import java.util.Collections;

import java.util.HashMap;

import java.util.HashSet;

import java.util.List;

import java.util.Map;

import java.util.Set;

import java.util.TreeMap;

public class CountDuplicatedList {

  public static void main(String[] args) {

List<String> list = new ArrayList<String>();

list.add("a");

list.add("b");

list.add("c");

list.add("d");

list.add("b");

list.add("c");

list.add("a");

list.add("a");

list.add("a");

System.out.println("\nExample 1 - Count 'a' with frequency");

System.out.println("a : " + Collections.frequency(list, "a"));

System.out.println("\nExample 2 - Count all with frequency");

Set<String> uniqueSet = new HashSet<String>(list);

for (String temp : uniqueSet) {

System.out.println(temp + ": " + Collections.frequency(list, temp));

}

System.out.println("\nExample 3 - Count all with Map");

Map<String, Integer> map = new HashMap<String, Integer>();

for (String temp : list) {

Integer count = map.get(temp);

map.put(temp, (count == null) ? 1 : count + 1);

}

printMap(map);

System.out.println("\nSorted Map");

Map<String, Integer> treeMap = new TreeMap<String, Integer>(map);

printMap(treeMap);

  }

  public static void printMap(Map<String, Integer> map){

for (Map.Entry<String, Integer> entry : map.entrySet()) {

System.out.println("Key : " + entry.getKey() + " Value : "

+ entry.getValue());

}

  }

}

Output

Example 1 - Count 'a' with frequency

a : 4

Example 2 - Count all with frequency

d: 1

b: 2

c: 2

a: 4

Example 3 - Count all with Map

Key : d Value : 1

Key : b Value : 2

Key : c Value : 2

Key : a Value : 4

Sorted Map

Key : a Value : 4

Key : b Value : 2

Key : c Value : 2

Key : d Value : 1
asked Sep 11 in Java Interview Questions by Amrendra | 9 views



Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

Related Questions



Welcome to Knowledge Boostr, where you can ask questions and receive answers from other members of the community.
This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers http://boostr.in Q&A for professional and enthusiast programmers


23,471 questions
40,135 answers
12 comments
23,609 users