Create KeyValue Tuple from a List collection in Java


To create KeyValue tuple from List collection, use the fromCollection() method. Let us first see what we need to work with JavaTuples. To work with KeyValue class in JavaTuples, you need to import the following package:

import org.javatuples.KeyValue;

Note: Download JavaTuples Jar library to run JavaTuples program. If you are using Eclipse IDE, then Right Click Project → Properties → Java Build Path → Add External Jars and upload the downloaded JavaTuples jar file. Refer the below guide for all the steps to run JavaTuples:

Steps: How to run JavaTuples program in Eclipse

The following is an example to create KeyValue Tuple from List collection in Java:

Example

import org.javatuples.KeyValue;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      List<String> myList = new ArrayList<String>();
      myList.add("One");
      myList.add("Two");
      KeyValue<String, String> kValue = KeyValue.fromCollection(myList);
      System.out.println(" KeyValue Tuple = "+kValue);
   }
}

Output

KeyValue Tuple = [One, Two]

Above, we have first created a List collection and added two elements:

List<String> myList = new ArrayList<String>();
myList.add("One");
myList.add("Two");

Now, to create KeyValue tuple from a List, use the fromCollection() method with the parameter as the above created List:

KeyValue<String, String> kValue = KeyValue.fromCollection(myList);

Updated on: 30-Jul-2019

67 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements