3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】MapをListに変換する方法

Posted at

#はじめに

本記事ではMapをListに変換する2通りの方法をアウトプットします。

#Listを直接生成する方法

Map<String, String> TopBillionaires = new LinkedHashMap<>();
		TopBillionaires.put("$195bn", "Elon Musk");
		TopBillionaires.put("$185bn", "Jeff Bezos");
		TopBillionaires.put("$134bn", "Bill Gates");
		TopBillionaires.put("$102bn", "Mark Zuckerberg");
		TopBillionaires.put("$88.2bn", "Warren Buffett");
		TopBillionaires.put("$81bn", "Sergey Brin");

		List<String> keyList = new ArrayList<>(TopBillionaires.keySet());
		List<String> valueList = new ArrayList<>(TopBillionaires.values());

		System.out.println(keyList);
		System.out.println(valueList);

        //出力
        // [$195bn, $185bn, $134bn, $102bn, $88.2bn, $81bn]
        // [Elon Musk, Jeff Bezos, Bill Gates, Mark Zuckerberg, Warren Buffett, Sergey Brin]

#Streamを利用する方法
以下では、StreamのCollectメソッドにCollectorsクラスのtoCollectionメソッドを渡しています。
出力結果はListを直接生成する方法と同じです。

Map<String, String> TopBillionaires = new LinkedHashMap<>();
		TopBillionaires.put("$195bn", "Elon Musk");
		TopBillionaires.put("$185bn", "Jeff Bezos");
		TopBillionaires.put("$134bn", "Bill Gates");
		TopBillionaires.put("$102bn", "Mark Zuckerberg");
		TopBillionaires.put("$88.2bn", "Warren Buffett");
		TopBillionaires.put("$81bn", "Sergey Brin");

        List<String> keyList = TopBillionaires.keySet().stream()
                .collect(Collectors.toCollection(ArrayList::new));
        List<String> valueList = TopBillionaires.values().stream()
                .collect(Collectors.toCollection(ArrayList::new));

        System.out.println(keyList);
        System.out.println(valueList);

        //出力
        // [$195bn, $185bn, $134bn, $102bn, $88.2bn, $81bn]
        // [Elon Musk, Jeff Bezos, Bill Gates, Mark Zuckerberg, Warren Buffett, Sergey Brin]

#参照
Java Platform SE8 #インタフェースStream

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?