Here you can find the source of extractRankedProducts( List
Parameter | Description |
---|---|
unsortedProducts | list of products with out any sorting |
public static List<String> extractRankedProducts( List<String> unsortedProducts)
//package com.java2s; //License from project: Open Source License import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; public class Main { /**//from w w w . j ava 2s. co m * Extracts the products which occurred more than once in the unsorted list and sorts them * based on their occurrence * @param unsortedProducts list of products with out any sorting * @return products sorted by ranking occurrence and that occurred more than 1 time */ public static List<String> extractRankedProducts( List<String> unsortedProducts) { final Map<String, Integer> occurencesMap = createOccurrenceMap(unsortedProducts); Comparator<String> comparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { Integer occurenceO1 = occurencesMap.get(o1); Integer occurenceO2 = occurencesMap.get(o2); int comparedOccurence = occurenceO2.compareTo(occurenceO1); return comparedOccurence; } }; List<String> sortedList = new ArrayList<String>( new HashSet<String>(unsortedProducts)); Collections.sort(sortedList, comparator); int i = 0; while (i < sortedList.size()) { if (occurencesMap.get(sortedList.get(i)) == 1) { sortedList.remove(i); } else { i++; } } return sortedList; } public static Map<String, Integer> createOccurrenceMap( List<String> unsortedProducts) { Map<String, Integer> occurencesMap = new HashMap<String, Integer>(); for (String recommendedItem : unsortedProducts) { if (occurencesMap.containsKey(recommendedItem)) { occurencesMap.put(recommendedItem, occurencesMap.get(recommendedItem) + 1); } else { occurencesMap.put(recommendedItem, 1); } } return occurencesMap; } }