簡體   English   中英

在地圖界面上應用過濾器和地圖后,如何同時顯示鍵和值?

[英]How to display both key and value after applying filter and map on Map Interface?

//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和名稱,因此上述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));

如果輸出不是您想要的,則意味着流返回的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和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 filter()流元素,它返回了學生元素的流,即您迭代遍歷的student(131),student(101)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM