在地图界面上应用过滤器和地图后如何同时显示键和值?


//i have a list of student type 
List<Student> list2 = new ArrayList<>();
list2.add(new Student(101, "piyush"));
list2.add(new Student(102, "Raman"));
list2.add(new Student(109, "Raman"));
//i converted this list to Map


Map<Integer, String> map3=list2.stream()
.collect(Collectors.
toMap(Student::getStudentId, Student::getStudName ));
//now i converted it to stream and applied some fiter and map
map3.entrySet()
.stream().filter(i -> i.getKey()==131 || i.getKey()==101).map(i-> i.getValue().toUpperCase())
.forEach(System.out::println);

//above code displays only name in UpperCase

但是我想同时显示ID和名称(大写(该怎么办。

map3.entrySet()
.stream().filter(i -> i.getKey()==131 || i.getKey()==101)
.forEach(System.out::println);

/此代码同时显示 id 和名称,因此上面的 forEach 循环不会显示它。 我什至尝试使用收集器将结果存储在地图中,但这不起作用。/

不工作

Map<Integer,String> map4= map3.entrySet()
.stream().filter(i -> i.getKey()==131 || i.getKey()==101).map(i-> i.getValue().toUpperCase()).
collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));

如果输出不是你想要的,这意味着你的流返回的Map.Entry实现可能不会覆盖ObjecttoString,所以你必须指定如何打印条目:

map3.entrySet()
.stream().filter(e -> e.getKey() == 131 || e.getKey() == 101)
.forEach(e -> System.out.println(e.getKey() + " " + e.getValue().toUpperCase()));

但是,查看您的完整代码,我不确定您首先需要创建该地图。您可以过滤原始列表并获得相同的输出:

list2.stream()
.filter(s -> s.getStudentId() == 131 || s.getStudentId() == 101)
.forEach(s -> System.out.println(s.getStudentId() + " " + s.getStudName ().toUpperCase()));

顺便说一句,如果您的原始列表包含多个具有相同 ID 的Student,那么您的Collectors.toMap将失败。

此代码同时显示 id 和名称,因此上面的 forEach 循环不会显示它

  • 以下代码片段未显示键导致中间操作.map(i-> i.getValue().toUpperCase())处理来自学生值元素(i-> i.getValue()(的流和返回流的元素。

    map3.entrySet()
    stream().filter(i -> i.getKey()==131 || i.getKey()==101).map(i->i.getValue().toUpperCase())
    .forEach(System.out::println);
    
  • 以下代码显示键和值,因为您只需要filter()流元素,它就会返回您遍历的学生元素流,即学生(131(、学生(101(。

    map3.entrySet()
    .stream().filter(i -> i.getKey()==131 || i.getKey()==101)
    .forEach(System.out::println);
    

最新更新