2017-10-25 3 views
1

は、私は次のString []をjava lambdaの合計値として配列インデックスでマップする方法?

new ConstructStateMachine(new String[] { 
     "a", "b", "c", "aa", "d", "b" 
}, 1, 5); 

ていると私はMap<String, Integer>に、この配列に変換したいと思います。

文字列は配列内の文字列要素がマップ内のキーになり、値は整数のリストとして値の配列のインデックスになります。

私はまた重複キーを保持する必要がありますが、Mapでは不可能ですが、解決策は重複キーを無視することですが、重複キーの値を集計し、Listを持たずにIntegerを重複キーのすべての値の合計を持つ値。

たちは、このテーブルを持っていると言う:

indices | 0 | 1 | 2 | 3 | 4 | 5 | 
item | a | b | c | aa | d | b | 
value | 1 | 2 | 3 | 4 | 5 | 6 | 

だから、私たちの地図は以下に保つ必要があります。

// pseudo-code 
Map<String, Integer> dictionary = new HashMap<>(
    ("b" => 8) // because "b" appeared in index 1 and 5 
    ("c" => 3) 
    ("aa" => 4) 
    ("d" => 5) 
); 

私の不完全な解決策:

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


// I thought of doing an intersection of two arrays and get the value from there 
// but that just made things more complicated 
String[] a = (Arrays.stream(dictionary) 
    .filter(x - > Arrays.stream(newDis) 
    .anyMatch(y - > Objects.equals(y, x)) 
) 
).toArray(String[]::new); 


// in here, I tried looping and created the value that starts from 1 to 6, rather than 
// from 0 to 5 
IntStream.range(0, this.newDis.length).forEach(idx - > { 
    List<Integer> currentValue = table.computeIfAbsent(newDis[idx], k - > new ArrayList<>()); 
    currentValue.add(idx + 1); 
}); 

をしかし、私は単に私の文字列を変換カント配列to Map<String, Integer>

+0

ラムダは、このタスクに悪いフィットのように思えます。ドライバーを持っていて、x-boxコントローラーとして使用しようとしているような感じです。方法を書くことを検討してください。 – DwB

+0

よく似ています。申し訳ありませんが、私はそのラムダか良い古いOOPの気にしません。 – OOP

答えて

5
IMO
String[] array = new String[] {"a", "b", "c", "aa", "d", "b"}; 
Map<String, Integer> result = 
    IntStream.range(0, array.length) 
      .boxed() 
      .collect(Collectors.toMap(i -> array[i], i -> i + 1, Integer::sum)); 

や、コードをよりredableで直感的になり、単純なループ、と、:

Map<String, Integer> result = new HashMap<>(); 
for (int i = 0; i < array.length; i++) { 
    result.merge(array[i], i + 1, Integer::sum); 
} 
+0

JBを入れましょう!すぐにお返事ありがとう:) – OOP

+1

'String [] array = {" a "、" b "、" c "、" aa "、" d "、" b "という単純な配列を宣言できます。 }; '、新しい文字列[]がない... – Holger

関連する問題