Created
February 25, 2021 00:33
-
-
Save lucoram/020a5539625a80a6d813df93a3a2cb67 to your computer and use it in GitHub Desktop.
Categorize products
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
public class Main { | |
public static void main(String[] args) { | |
// Assumptions: | |
// - list contains unique products | |
// - multiple products can share the same category | |
// - categories are ordered alphabetically | |
// - products keep the order the appear in the list | |
// - list contains only lowercase english letters | |
// - list entry format is <product>:<category> | |
String[] productsList = { | |
"apple:fruit", | |
"coca:drink", | |
"orange:fruit", | |
"pepsi:drink", | |
"banana:fruit" | |
}; | |
groupByCategory(productsList); | |
} | |
private static void groupByCategory(String[] productsList) { | |
Map<String, List<String>> productsPerCategory = new HashMap<>(); | |
for(String prodEntry : productsList) { | |
String[] parts = prodEntry.split(":"); | |
String prod = parts[0]; | |
String cat = parts[1]; | |
if(!productsPerCategory.containsKey(cat)) { | |
productsPerCategory.put(cat, new ArrayList<>()); | |
} | |
productsPerCategory.get(cat).add(prod); | |
} | |
List<String> categories = new ArrayList<>(productsPerCategory.keySet()); | |
Collections.sort(categories); | |
for(String cat : categories) { | |
System.out.println(cat + ":"); | |
for(String prod : productsPerCategory.get(cat)) { | |
System.out.println("\t" + prod); | |
} | |
} | |
} | |
} |
simplify Map creation:
Map<String, List<String>> productsPerCategory = Arrays.asList(productsList).stream().map(product -> product.split(":")) .collect(Collectors.groupingBy(produit -> produit[1], Collectors.mapping(produit -> produit[0], Collectors.toList())));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PHP :