将值存储在单独的映射中,以便在java中到达特定字符

时间:2016-04-30 08:36:41

标签: java arraylist

我有以下字符串

INPUT:

1 APPLE 
2 BANANA

我想创建2个不同的地图并传递

的值
1 ORANGE
6 GRAPES

到一张地图,同样地,

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <View
        android:id="@+id/dummy"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerInParent="true"
    />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back"
        android:textColor="@color/white"
        android:id="@+id/button4"
        android:onClick="onBackClick"
        android:layout_toLeftOf="@id/dummy"
        android:background="@android:color/darker_gray"
    />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button4"
        android:text="login"
        android:textColor="@color/white"
        android:minWidth="130dp"
        android:id="@+id/button3"
        android:layout_toLeftOf="@id/dummy"
        android:layout_marginLeft="10dp"
        android:onClick="onSigninClick"
        android:background="@android:color/holo_green_light"
    />
</RelativeLayout>

为其他地图。这些值来自单个数组列表,我希望在到达字符“:”时开始拆分。任何帮助都会很棒

2 个答案:

答案 0 :(得分:2)

由于一些澄清,我能够根据您的问题调整我的答案。

Map<Integer, String> horizontal = new HashMap<>();
Map<Integer, String> vertical = new HashMap<>();
boolean horiz = true;
for(String line: al2){
  if(line.contains(":")) horiz = false;
  else if(line.trim().length() > 0) {
    String[] splitted = line.split(" ");
    if(horiz) horizontal.put(Integer.valueOf(splitted[0]), splitted[1]);
    else vertical.put(Integer.valueOf(splitted[0]), splitted[1]);
  }
}

答案 1 :(得分:0)

在你的输出中,你消除了DOWN :,我认为它是一个不在实际输出之外的标记。

基本上,您创建了一个从循环内部切换的迷你状态机。使用1布尔值,这是可管理的,但有多个值我建议创建一个状态对象。

List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();

// obviously name this after the actual purpose secondlist serves
// e.g. storeAddressDetails or whatever your usecase is
boolean putInSecondList = false;

for(String line : lines) {
    if (line.trim().isEmpty()) {
        // ignore whitespace
        continue;
    }
    if (line.contains(":")) {
        // skip and set passedMarker
        passedMarker = true;
        continue;
    }
    if (putInSecondList == false) {
        list1.add(line);
    } else {
        list2.add(line);
    }
}