Java使用stream()和filter()获取嵌套映射的运行总数
假设我有一张地图,它的键也是一张地图Java使用stream()和filter()获取嵌套映射的运行总数,java,Java,假设我有一张地图,它的键也是一张地图 Map<Map<String, Integer>, Integer> Map 我想计算外部映射值的运行和 如果外部映射的键的值与给定的 我有以下代码 import java.util.HashMap; import java.util.Map; public class Main{ public static void main(String []args){ Map<Map<String,
Map<Map<String, Integer>, Integer>
Map
我想计算外部映射值的运行和
如果外部映射的键的值与给定的
我有以下代码
import java.util.HashMap;
import java.util.Map;
public class Main{
public static void main(String []args){
Map<Map<String, Integer>, Integer> courses = new HashMap<Map<String,Integer>,Integer>();
Map<String,Integer> temp = new HashMap<String, Integer>();
temp.put("CS 111", 1);
Map<String,Integer> temp2 = new HashMap<String, Integer>();
temp2.put("CS 222", 2);
Map<String,Integer> temp3 = new HashMap<String, Integer>();
temp2.put("CS 333", 1);
courses.put(temp, 3);
courses.put(temp2, 5);
courses.put(temp3, 7);
//sum should be 10
int sum = courses.entrySet()
.stream()
.filter(m ->m.getKey()
.stream()
.anyMatch(t->t.getValue()==1)
.reduce(0,Integer::sum));
}
}
import java.util.HashMap;
导入java.util.Map;
公共班机{
公共静态void main(字符串[]args){
Map courses=newhashmap();
Map temp=newhashmap();
温度输入(“CS 111”,1);
Map temp2=新的HashMap();
temp2.put(“cs222”,2);
Map temp3=新的HashMap();
temp2.put(“CS 333”,1);
课程设置(临时,3);
课程。put(temp2,5);
课程。put(temp3,7);
//总数应该是10
int sum=courses.entrySet()
.stream()
.filter(m->m.getKey()
.stream()
.anyMatch(t->t.getValue()==1)
.reduce(0,Integer::sum));
}
}
在过滤器中,您可以使用Map.values()
获取映射的值,从而使其更具可读性。过滤后,您可以使用易于统计的Stream.mapToInt
。例如:
Map<Map<String,Integer>, Integer> myMap =
Map.of(
Map.of("CS 111", 1), 3,
Map.of("CS 222", 2), 5,
Map.of("CS 333", 1), 7
);
int sum = myMap.entrySet()
.stream()
.filter(e -> e.getKey().containsValue(1))
.mapToInt(Map.Entry::getValue).sum();
System.out.println(sum);
Map myMap=
地图(
地图(“CS 111”,1),3,
地图(“CS 222”,2),5,
地图(“CS 333”,1),7
);
int sum=myMap.entrySet()
.stream()
.filter(e->e.getKey().containsValue(1))
.mapToInt(Map.Entry::getValue).sum();
系统输出打印项数(总和);
非常清楚,谢谢]@Eritrean e.getKey().values().contains(1))可以替换为e.getKey().containsValue(1),如果您想保存几个字符。@HomeworkHopper谢谢。它确实更好、更清晰。使用地图作为钥匙是非常不寻常的(可能效率低下且不可读)。如果内部映射有多个条目怎么办?如果内部映射只能有一个条目,为什么不将键设为条目而不是映射?