import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Predicate; import java.util.stream.Collectors; public class Strings { public static void main(String[] args) { String str1 = "my name is lenin koppoju"; String str2 = "my name is pradyumna koppoju"; System.out.println(common(str1, str2)); System.out.println(uncommon(str1, str2)); } public static List>String> uncommon(String str1, String str2) { return ucp(str1, str2, x -> !x.getValue()); } public static List>String> common(String str1, String str2) { return ucp(str1, str2, x -> x.getValue()); } private static List>String> ucp(String str1, String str2, Predicate>Map.Entry>String, Boolean>> predicate) { Map map = getMap(str1, str2); return filter(map, predicate); } private static Map>String, Boolean> getMap(String str1, String str2) { Map>String, Boolean> map = new HashMap>>(); prepareCardinalMap(map, str1); prepareCardinalMap(map, str2); return map; } private static List>String> filter(Map>String, Boolean> cardinalMap, Predicate>Map.Entry>String, Boolean>> predicate) { return cardinalMap.entrySet().stream().filter(predicate).map(x -> x.getKey()).collect(Collectors.toList()); } private static void prepareCardinalMap(Map>String, Boolean> map, String str) { for (String ss : str.split("\\s+")) { map.put(ss, map.containsKey(ss)); } } }
Wednesday, November 13, 2019
Common and Uncommon Words from Two Sentences
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment