오늘 루트 필터링을 작성할 때 약간 기절했습니다. 나는 처음으로 Java Native Map을 사용하여 그것을 루프하는 것을 생각했지만 너무 낮다고 생각했습니다. 나중에 나는 그것에 대해 생각하고 Java 8 Lambda를 사용할 수있었습니다. 그것을 작성한 후 Google Guava는 기성품 방법을 가지고 있음을 알았습니다. 나는 참조를 위해 하나씩 하나씩 나열했다.
우선, 내 코드를 복사하면 이러한 종속성을 인용하는 것을 잊지 마십시오.
<pectionies> <pectinement> <groupId> junit> <artifactid> junit </artifactid> <bersion> 4.12 </version> <cope> test </scope> <제외> <groupId> org.hamcrest </groupid> hamcrest-comecore> </fexcusion> </explusion> </explusion> <groupid> org.hamcrest </groupid> <artifactid> hamcrest-library </artifactid> <bersion> 1.3 </version> <cope> test </scope> </dependency> <prectionency> <groupId> com.goova.guava </groupid> <artifactid> guava </artifactid> <버전> 25.1-jree </version> </종속성> </종속성>
키에 의해 필터
공개 클래스 FiltermapByKeyTest {private map <integer, string> week = new Hashmap <> (); @public void setup () {week.put (1, "월요일"); Week.put (2, "화요일"); Week.put (3, "수요일"); Week.put (4, "목요일"); Week.put (5, "금요일"); Week.put (6, "토요일"); Week.put (7, "일요일"); } / *** Java 이전의 버전 8* / @test public void filtermapbykey () {map <integer, string> map = new Hashmap <> (); for (map.Entry <integer, string> entry : week.entryset ()) {if (enther.getKey () <= 3) {map.put (enther.getKey (), enther.getValue ()); }} AssertThat (map.keyset (), 포함 (1, 2, 3)); } / ** * java 8 lambda * / @test public void filtermapbyjava8lambda () {map <integer, string> map = theing.entryset (). stream (). filter (r-> r.getkey () <= 3) .collect (collects.tomap (map.entry :: getkey, map. AssertThat (map.keyset (), (1, 2, 3)); } / ** * Google Guava * / @test public void filtermapbykeyguava () {map <integer, string> map = maps.filterkeys (주, r-> r <= 3); AssertThat (map.keyset (), (1, 2, 3)); }}값별로 필터
공개 클래스 FiltermapByValuetest {private map <integer, string> week = new Hashmap <> (); @public void setup () {week.put (1, "월요일"); Week.put (2, "화요일"); Week.put (3, "수요일"); Week.put (4, "목요일"); Week.put (5, "금요일"); Week.put (6, "토요일"); Week.put (7, "일요일"); } / *** Java 이전의 버전 8* / @test public void filtermapbyvalue () {map <integer, string> map = new Hashmap <> (); for (map.Entry <integer, string> entry : week.entryset ()) {if (enther.getValue (). startSwith ( "s")) {map.put (enther.getKey (), enther.getValue ()); }} AssertThat (map.values (), contains ( "토요일", "일요일")); } / ** * java 8 lambda * / @test public void public void filtermapbyvaluejava8lambda () {map <integer, string> map = theing.entryset (). stream (). filter (r-> r.getValue (). startswith ( "s"). map.entry :: getValue); AssertThat (map.values (), 포함 ( "토요일", "일요일")); } / ** * Google Guava * / @test public void filtermapbyvalueguava () {map <integer, string> map = maps.filterValues (주, r-> r.StartSwith ( "s")); AssertThat (map.values (), 포함 ( "토요일", "일요일")); }}요약
위는 편집기가 소개 한 키 또는 값을 통해 필터링 된 Java 맵의 예제 코드입니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!