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

时间:2017-08-06 09:20:21

标签: java java-8

//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和name(大写)我应该怎么做。

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

/ 此代码同时显示id和name,因此上面的forEach循环没有显示它。 我甚至尝试使用收集器将结果存储在Map中,但这不起作用。 /

//无法正常工作

    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));

2 个答案:

答案 0 :(得分:3)

如果输出不符合您的要求,则表示您的信息流返回的Map.Entry实施可能不会覆盖Object的{​​{1}},因此您必须指定如何打印条目:

toString

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

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

顺便说一句,如果您的原始列表包含多个具有相同ID的list2.stream() .filter(s -> s.getStudentId() == 131 || s.getStudentId() == 101) .forEach(s -> System.out.println(s.getStudentId() + " " + s.getStudName ().toUpperCase())); ,则Student将失败。

答案 1 :(得分:0)

  

此代码同时显示id和name,因此上面的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() stream元素,它返回学生元素的流,即学生(131),学生(101),你迭代过来。

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