我使用Java 8实现了以下代码。
Map<String, String> coMap = getHashMap();
String newCoName = coMap.entrySet()
.stream()
.filter(coEntry -> coEntry.getValue().equals(newcoId))
.map(coEntry -> coEntry.getKey())
.collect(Collectors.joining());
String oldCoName = coMap.entrySet()
.stream()
.filter(coEntry -> coEntry.getValue().equals(oldcoId))
.map(coEntry -> coEntry.getKey())
.collect(Collectors.joining());现在。我想知道更好的方法来做到这一点,而不是重复相同的代码行两次。
发布于 2016-12-22 09:21:42
因为所有的区别都是id,所以一个简单的方法就可以实现这一点。
String getName(int id) { // supposed id is an integer
return coMap.entrySet()
.stream()
.filter(coEntry -> coEntry.getValue().equals(id))
.map(coEntry -> coEntry.getKey())
.collect(Collectors.joining());
}发布于 2016-12-22 09:32:43
比重复两次相同的代码更大的问题是执行两次相同的代码。
运行一个Stream管道来生成您的输出会更有效:
Map<String,String> keysByValue =
coMap.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey,
Collectors.joining())));这将为原始Map的每个值(不仅是原始代码正在搜索的两个值)提供该值的联合键。
然后可以从Map中提取所需的数据:
String newCoName = keysByValue.get(newcoId);
String oldCoName = keysByValue.get(oldcoId);样本输入和输出:
Map<String,String> coMap = new HashMap<> ();
coMap.put("a","foo");
coMap.put("b","foo");
coMap.put("c","bar");
coMap.put("d","bar");
Map<String,String> keysByValue = ... // same as the code above
String newValueKeys = keysByValue.get("foo");
String oldValueKeys = keysByValue.get("bar");
System.out.println (newValueKeys);
System.out.println (oldValueKeys);产出:
ab
cd发布于 2016-12-22 09:42:00
与FunctionalInterface Predicate一起使用的其他方法,条件筛选器将是动态的。
public static Predicate<Map.Entry> getPredicate(String col) {
return p -> p.getValue().equals(col);
}
public static String getName(HashMap<String, String> coMap, Predicate<Map.Entry> predicate) {
return coMap.entrySet()
.stream()
.filter(predicate)
.map(coEntry -> coEntry.getKey())
.collect(Collectors.joining());
}调用您的代码:
getName(coMap, getPredicate(newcoId));
getName(coMap, getPredicate(oldcoId));https://stackoverflow.com/questions/41279574
复制相似问题