Saurabh Araiyer
Saurabh Araiyer

Reputation: 140

Create a map out of Object Java8

I have a class:

Class Sample {
  String first;
  String second;
}

I want to create a map like:

first->second

What will be the lambda expression to achieve this.

Upvotes: 0

Views: 48

Answers (2)

Tagir Valeev
Tagir Valeev

Reputation: 100199

Use plain old Collections.singletonMap():

Sample s = new Sample("first", "second");
Map<String, String> m = Collections.singletonMap(s.getFirst(), s.getSecond());

Upvotes: 1

Jean Logeart
Jean Logeart

Reputation: 53819

Try:

Sample s = new Sample("first", "second");
Map<String, String> m = 
    Stream.of(s)
          .collect(Collectors.toMap(Sample::getFirst, Sample::getSecond));

Upvotes: 2

Related Questions