0

I have a query string like

"1_timestamp=201612312&1_user=123&2_timestamp=20145333&2_user=5432";

But I want to make them in array like below.

array(
    0 => (
        timestamp = 201612312,
        user = 123,
        ),
    1 => (
        timestamp = 201612312,
        user = 123,
        ),
);

I'm sorry to show you php type of array though I'm new to java.

How do I make it something like that?

Thank you

6
  • 2
    Think of Map. Commented Nov 24, 2016 at 6:59
  • 2
    Write classes and create objects to represent your data instead of creating a multidiminesional array. Commented Nov 24, 2016 at 7:02
  • Do you want to parse the string 1_timestamp=201612312&1_user=123&2_timestamp=20145333&2_user=5432? Commented Nov 24, 2016 at 7:47
  • @MCEmperor Parsing the string is not a big deal but arranging the string and put them into object is difficult for me Commented Nov 24, 2016 at 7:48
  • @EricLee You just caught the whole point of object-orientation. You have two related properties (timestamp and user), and they belong in a class (possibly named Visit or something?). You should just follow @apadana's format. Commented Nov 24, 2016 at 9:02

2 Answers 2

2

This is the closest structure to what you are doing in php, and if your data has more fields it can be easily added to the Data class:

import java.util.ArrayList;
import java.util.List;

class Data {
    int timestamp;
    int user;

    Data(int ts, int user) {
        this.timestamp = ts;
        this.user = user;
    }
}

public class Test {

    public static void main(String[] args) {
        List<Data> data = new ArrayList<Data>();
        Data d1 = new Data(201612312, 123);
        Data d2 = new Data(201612312, 123);
        data.add(d1);
        data.add(d2);

        System.out.println(data.get(1).user);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you!! This is not the perfect one I was looking for though, This helped me got a point of figuring out how to solve the issue.
1

You can do it without writing a class. You can use it like this.

Map<String, String> map1 = new HashMap<String, String>();
map1.put("1_timestamp", "201612312");
map1.put("1_user", "123");

Map<String, String> map2 = new HashMap<String, String>();
map2.put("2_timestamp", "20145333");
map2.put("2_user", "5432");

List<Map<String,String> mapList = new ArrayList<Map<String, String>>();
mapList.add(map1);
mapList.add(map2);

for (Map<String, String> map : list) {
    for (Map.Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + " - " + entry.getValue());
    }
}

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.