viespring
viespring

Reputation: 41

Tuple in Java lang

I would like to do something with Java like Python.

data = [
    ('1','One'),
    ('2','Two'),
    ('3','Three')
] # Please, Java, how can do that ?

### List<Integer, Double> data = new ArrayList<Integer, Double>() ???
### Or
### ArrayList<Integer, Double> data = new ArrayList<>() ????
## Or more ???

for datium in data:
    print(f"{datium[0]} - {datium[1]}")

Please help.

Upvotes: 1

Views: 4141

Answers (3)

Kaplan
Kaplan

Reputation: 3758

use of record
since Java 16
preview in Java 14:
https://docs.oracle.com/en/java/javase/14/language/records.html

record Pair(String n, String s) {};

Pair[] data = {             /* as array */
    new Pair("1", "One"),
    new Pair("2", "Two"),
    new Pair("3", "Three")};

List<Pair> data = List.of(  /* as list */
    new Pair("1", "One"),
    new Pair("2", "Two"),
    new Pair("3", "Three"));

(You should define more meaningful variable names, depending on the use case in Pair)

Upvotes: 1

Amol Thakurdware
Amol Thakurdware

Reputation: 1

Well not exactly the same. But this should solve your purpose.

package solutions;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class MapExample {

    public static void main(String[] args) {
        Map<Integer, String> m=new HashMap<Integer, String>();
        m.put(1, "One");
        m.put(2, "Two");
        m.put(3, "Three");
        
        Set<Integer> keySet = m.keySet();
        for(Integer key:keySet) {
            System.out.println(key+"  "+m.get(key));
        }
        
    }

}

Upvotes: 2

JP Moresmau
JP Moresmau

Reputation: 7403

There are no first-class support for Tuples in Java. You can

Upvotes: 2

Related Questions