Skip to main content
  1. About
  2. For Teams
Asked
Viewed 4k times
1

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.

2
  • There aren't any integers in your Python code there. That's a list of tuples of strings. Java doesn't have tuples, so there isn't really an equivalent. You could use a List<List<String>> if you want. Or write a class.
    khelwood
    –  khelwood
    2021-05-01 09:55:47 +00:00
    Commented May 1, 2021 at 9:55
  • BTW we can do Map.of('1', "One", '2', "Two", '3', "Three")
    user85421
    –  user85421
    2023-11-20 13:40:48 +00:00
    Commented Nov 20, 2023 at 13:40

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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));
        }
        
    }

}

Comments

1

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)

1 Comment

This is actually as close as we can get to tuples in Java. I will only add that to access the field, use the name with () e.g. p.n() or p.s() for the above example

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.