java8 stream處理

1.處理list轉Map保持有序:LinkedHashMap

  • 例子1:
List<Bean> list = new ArrayList<>();

Map<String, Bean> map = list.stream()
  .collect(Collectors.toMap(Bean::getId, o -> o, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
  • 例子2:
Map<String, Object> map = new LinkedHashMap<>();
  • 例子3:
import com.google.common.collect.Maps;
Map<String, String> map = Maps.newLinkedHashMap();

底層:
/**
 * Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance.
 *
 * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead.
 *
 * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as
 * deprecated. Instead, use the {@code LinkedHashMap} constructor directly, taking advantage of
 * the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>.
 *
 * @return a new, empty {@code LinkedHashMap}
 */
public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
  return new LinkedHashMap<>();
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章