今日ルートフィルタリングを書いていたとき、私は少しun然としました。私は最初にJavaネイティブマップを使用してループアウトすることを考えましたが、それは低すぎると思いました。後で、私はそれについて考え、Java 8 Lambdaを使用できます。書いた後、Google Guavaには既製の方法があることがわかりました。参照のために1つずつリストしました。
まず第一に、私のコードをコピーする場合、これらの依存関係を引用することを忘れないでください
<dependencies> <Dependency> <groupId> junit </groupid> <artifactid> junit </artifactid> <version> 4.12 </version> <scope> test </scope> <explusion> <exclusion> <groupid> org.hamcrest </groupid> </groupid> <artifactid> hamcrest-core </artifactid> </explency> </explency> <groupid> org.hamcrest </groupid> <artifactid> hamcrest-library </artifactid> <version> 1.3 </version> <scope> test </scope> </dependency> <redency> <groupid> com.google.guava </groupid> <artifactid> guava </artifactid> </jre </dependency> </dependencies>
キーごとにフィルター
public class filtermapbykeytest {private map <integer、string> week = new hashmap <>(); @before public void setup(){week.put(1、 "monday"); week.put(2、 "火曜日"); week.put(3、 "水曜日"); week.put(4、 "木曜日"); week.put(5、 "Friday"); week.put(6、 "土曜日"); week.put(7、 "Sunday"); } / *** java 8の前のバージョン* / @test public void filtermapbykey(){map <integer、string> map = new hashmap <>(); for(map.entry <integer、string> entry:week.entryset()){if(entry.getKey()<= 3){map.put(entry.getKey()、entry.getValue()); }} assertthat(map.keyset()、contas(1、2、3)); } / ** * java 8 lambda * / @test public void filtermapbykeyjava8lambda(){map <integer、string> map = week.entryset()。 assertthat(map.keyset()、contas(1、2、3)); } / ** * Google guava * / @test public void filtermapbykeyguava(){map <integer、string> map = maps.filterkeys(week、r-> r <= 3); assertthat(map.keyset()、contas(1、2、3)); }}値でフィルター
public class filtermapbyvaluetest {private map <integer、string> week = new hashmap <>(); @before public void setup(){week.put(1、 "monday"); week.put(2、 "火曜日"); week.put(3、 "水曜日"); week.put(4、 "木曜日"); week.put(5、 "Friday"); week.put(6、 "土曜日"); week.put(7、 "Sunday"); } / *** java 8* / @test public void filtermapbyvalue(){map <integer、string> map = new hashmap <>(); for(map.entry <integer、string> entry:week.entryset()){if(entry.getValue()。startswith( "s")){map.put(entry.getKey()、entry.getValue()); }} assertthat(map.values()、contains( "土曜日"、 "日曜日")); } / ** * java 8 lambda * / @test public void filtermapbyvaluejava8lambda(){map <integer、string> map = week.entryset()。 assertthat(map.values()、contas( "土曜日"、「日曜日」)); } / ** * Google guava * / @test public void filtermapbyvalueguava(){map <integer、string> map = maps.filtervalues(week、r-> r.startswith( "s")); assertthat(map.values()、contas( "土曜日"、「日曜日」)); }}要約します
上記は、編集者によって導入されたキーまたは値を介してフィルタリングされたJavaマップのコードの例です。私はそれが誰にでも役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は、すべての人に時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!