博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

map 根据value 筛选

Posted on 2022-10-21 16:54  和风细雨汪汪  阅读(634)  评论(0编辑  收藏  举报

filter by key

public class FilterMapByKeyTest {
  private Map<Integer, String> WEEK = new HashMap<>();
  @Before
  public void setUp () {
    WEEK.put(1, "Monday");
    WEEK.put(2, "Tuesday");
    WEEK.put(3, "Wednesday");
    WEEK.put(4, "Thursday");
    WEEK.put(5, "Friday");
    WEEK.put(6, "Saturday");
    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(), contains(1, 2, 3));
  }
  /
*
   * Java 8 Lambda
   /
  @Test
  public void filterMapByKeyJava8Lambda () {
    Map<Integer, String> map = WEEK.entrySet().stream().filter(r -> r.getKey() <= 3)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    assertThat(map.keySet(), contains(1, 2, 3));
  }
  /
*
   * Google Guava
   */
  @Test
  public void filterMapByKeyGuava () {
    Map<Integer, String> map = Maps.filterKeys(WEEK, r -> r <= 3);
    assertThat(map.keySet(), contains(1, 2, 3));
  }
}

filter by value

public class FilterMapByValueTest {
  private Map<Integer, String> WEEK = new HashMap<>();
  @Before
  public void setUp () {
    WEEK.put(1, "Monday");
    WEEK.put(2, "Tuesday");
    WEEK.put(3, "Wednesday");
    WEEK.put(4, "Thursday");
    WEEK.put(5, "Friday");
    WEEK.put(6, "Saturday");
    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("Saturday","Sunday"));
  }
  /
*
   * Java 8 Lambda
   /
  @Test
  public void filterMapByValueJava8Lambda () {
    Map<Integer, String> map = WEEK.entrySet().stream().filter(r -> r.getValue().startsWith("S"))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    assertThat(map.values(), contains("Saturday","Sunday"));
  }
  /
*
   * Google Guava
   */
  @Test
  public void filterMapByValueGuava () {
    Map<Integer, String> map = Maps.filterValues(WEEK, r -> r.startsWith("S"));
    assertThat(map.values(), contains("Saturday","Sunday"));
  }
}