0

I'm looking for something that is surely very simple, but I don't know the best way to do it.

I could have 2 arrays of strings (that I don't know size at start), containing something like:

down[0]:"file1"
down[1]:"file2"
...
up[0]:"file3"
up[1]:"file4"
...

But I'd like them in the same array like:

array["down"][0]:"file1"
array["down"][1]:"file2"
array["up"][0]:"file3"
array["up"][1]:"file4"

And insert data with:

array[mykey].put(filename);

And loop through the data with:

for (String st : array["down"])
...
for (String st : array["up"])
...

Thanks for your ideas.

1
  • Hmm. I never saw array indexed with string. As I know, this is not possible. If I am wrong correct me. If you want to do such a thing you should make a method where output is int and looks like array[yourMethod("down")]. Just try to find "down" in an array and make index as an output Commented Dec 4, 2018 at 19:35

2 Answers 2

1

It sounds like you want a MutableMap<String, MutableList<String>>. In Kotlin, for example:

val data = mutableMapOf(
  "down" to mutableListOf("file1", "file2"),
  "up" to mutableListOf("file3", "file4")
)

Then you can access like:

data["down"].forEach { file ->
  // do something with file
}

Or mutate it like:

data["down"].add("file5")

For Java, you'll have to be a bit more verbose, but you can accomplish a similar result:

Map<String, List<String>> data = new HashMap<>();

List<String> downList = new ArrayList<>();
downList.add("file1");
downList.add("file2");
data.put("down", downList);

List<String> upList = new ArrayList<>();
upList.add("file3");
upList.add("file4");
data.put("up", upList);

Then:

for (String file : data.get("down")) {
  // do something with file
}

Or mutate it like:

data.get("down").add("file5");
Sign up to request clarification or add additional context in comments.

2 Comments

Sorry, I don't use Kotlin.
Ah okay, I wasn't sure from the tags. I've updated to include a Java answer too. Same data structures apply, it's just more verbose.
0

if you are using Kotlin you could do

val data : MutableMap<String,MutableList<String>> = mutableMapOf()
data["up"] = mutableListOf()
data["down"] = mutableListOf()

// add file to up
data["up"]?.add("file1")

// get the first up
val firstUp = data["up"]?.get(0)

// map over all the ups if the are there
data["up"]?.forEach { str ->

    }

Comments

Your Answer

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.