我有一个包含宽字符串表的txt文件。我想将其转换为基于ID列的广泛列表。数据看起来像这样
Long format has 3 columns: country, key, value
- M*N rows.
e.g.
'USA', 'President', 'Obama'
...
'USA', 'Currency', 'Dollar'
Wide format has N=16 columns: county, key1, ..., keyN
- M rows
example:
country, President, ... , Currency
'USA', 'Obama', ... , 'Dollar'
我想知道
SELECT country,
MAX( IF( key='President', value, NULL ) ) AS President,
MAX( IF( key='Currency', value, NULL ) ) AS Currency,
...
FROM table
GROUP BY country;
在Java中!
答案 0 :(得分:1)
我认为您可以使用一些Collectors.groupingBy()使其更容易一些,但更简单的版本是这样:
List<String[]> list = new ArrayList<>();
list.add(new String[] { "USA", "President", "Obama" });
list.add(new String[] { "USA", "Currency", "Dollar" });
list.add(new String[] { "Germany", "President", "Steinmeier" });
list.add(new String[] { "Germany", "Currency", "Euro" });
list.add(new String[] { "United Kingdom", "President", "Queen Elisabeth" });
list.add(new String[] { "United Kingdom", "Currency", "Pound" });
Map<String, Map<String, String>> map = new HashMap<>();
list.forEach(s -> {
map.putIfAbsent(s[0], new HashMap<>());
map.get(s[0]).put(s[1], s[2]);
});
List<String[]> wideList = map.entrySet().stream()
.map(m -> new String[] { m.getKey(), m.getValue().get("President"), m.getValue().get("Currency") })//
.collect(Collectors.toList());
System.out.println("country, President, Currency");
wideList.forEach(s -> System.out.println(s[0] + ", " + s[1] + ", " + s[2]));